BfModule.cpp 890 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(disable:4996)
  4. #pragma warning(push) // 6
  5. #include "BfCompiler.h"
  6. #include "BfSystem.h"
  7. #include "BfParser.h"
  8. #include "BfCodeGen.h"
  9. #include "BfExprEvaluator.h"
  10. #include "../Backend/BeLibManger.h"
  11. #include "BfConstResolver.h"
  12. #include "BfMangler.h"
  13. #include "BeefySysLib/util/PerfTimer.h"
  14. #include "BeefySysLib/util/BeefPerf.h"
  15. #include "BeefySysLib/util/StackHelper.h"
  16. #include "BfSourceClassifier.h"
  17. #include "BfAutoComplete.h"
  18. #include "BfDemangler.h"
  19. #include "BfResolvePass.h"
  20. #include "BfFixits.h"
  21. #include "BfIRCodeGen.h"
  22. #include "BfDefBuilder.h"
  23. #include "BfDeferEvalChecker.h"
  24. #include "CeMachine.h"
  25. #include "CeDebugger.h"
  26. #include <fcntl.h>
  27. #include <time.h>
  28. #pragma warning(pop)
  29. //////////////////////////////////////////////////////////////////////////
  30. static bool gDebugStuff = false;
  31. USING_NS_BF;
  32. //////////////////////////////////////////////////////////////////////////
  33. void BfLocalVariable::Init()
  34. {
  35. if (mResolvedType->IsValuelessType())
  36. {
  37. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  38. return;
  39. }
  40. if (mAssignedKind != BfLocalVarAssignKind_None)
  41. return;
  42. bool isStruct = mResolvedType->IsStruct();
  43. if (mResolvedType->IsRef())
  44. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  45. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  46. {
  47. auto resolvedTypeRef = mResolvedType;
  48. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  49. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  50. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  51. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  52. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  53. {
  54. // Base ctor is responsible for initializing its own fields
  55. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  56. }
  57. if (mUnassignedFieldFlags == 0)
  58. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  59. }
  60. else
  61. {
  62. mUnassignedFieldFlags = 1;
  63. }
  64. }
  65. BfLocalMethod::~BfLocalMethod()
  66. {
  67. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  68. if (mMethodDeclaration != NULL)
  69. {
  70. mSource->mRefCount--;
  71. BF_ASSERT(mSource->mRefCount >= 0);
  72. }
  73. delete mMethodInstanceGroup;
  74. delete mMethodDef;
  75. }
  76. void BfLocalMethod::Dispose()
  77. {
  78. if (mMethodInstanceGroup == NULL)
  79. return;
  80. if (mMethodInstanceGroup->mDefault != NULL)
  81. mMethodInstanceGroup->mDefault->Dispose();
  82. if (mMethodInstanceGroup->mMethodSpecializationMap != NULL)
  83. {
  84. for (auto& kv : *mMethodInstanceGroup->mMethodSpecializationMap)
  85. kv.mValue->Dispose();
  86. }
  87. }
  88. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  89. {
  90. mIsChained = doChain;
  91. if (outerLocalAssignData == NULL)
  92. return;
  93. mChainedAssignData = outerLocalAssignData;
  94. if (!doChain)
  95. {
  96. outerLocalAssignData->BreakExtendChain();
  97. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  98. }
  99. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  100. }
  101. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  102. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  103. // if ((GetValue(out a)) && (GetValue(out b)) {}
  104. void BfDeferredLocalAssignData::BreakExtendChain()
  105. {
  106. if (!mIsChained)
  107. return;
  108. mIsChained = false;
  109. if (mChainedAssignData == NULL)
  110. return;
  111. mChainedAssignData->BreakExtendChain();
  112. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  113. }
  114. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  115. {
  116. BreakExtendChain();
  117. if (otherLocalAssignData.mLeftBlockUncond)
  118. {
  119. // Intersection of self and infinity is self
  120. }
  121. else if (mLeftBlockUncond)
  122. {
  123. // Intersection of infinity and other is other
  124. mAssignedLocals = otherLocalAssignData.mAssignedLocals;
  125. }
  126. else
  127. {
  128. for (int i = 0; i < (int)mAssignedLocals.size(); )
  129. {
  130. auto& local = mAssignedLocals[i];
  131. bool wantRemove = true;
  132. bool foundOtherFields = false;
  133. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  134. {
  135. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  136. {
  137. if ((otherLocalAssignData.mLocalVarField == local.mLocalVarField) || (otherLocalAssignData.mLocalVarField == -1))
  138. {
  139. if (otherLocalAssignData.mAssignKind == BfLocalVarAssignKind_Conditional)
  140. local.mAssignKind = BfLocalVarAssignKind_Conditional;
  141. wantRemove = false;
  142. }
  143. else
  144. foundOtherFields = true;
  145. }
  146. }
  147. if ((wantRemove) && (foundOtherFields))
  148. {
  149. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  150. {
  151. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  152. {
  153. mAssignedLocals.Add(otherLocalAssignData);
  154. }
  155. }
  156. }
  157. if (wantRemove)
  158. {
  159. mAssignedLocals.RemoveAt(i);
  160. }
  161. else
  162. i++;
  163. }
  164. }
  165. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  166. mLeftBlockUncond = mLeftBlockUncond && otherLocalAssignData.mLeftBlockUncond;
  167. }
  168. void BfDeferredLocalAssignData::Validate() const
  169. {
  170. for (auto var : mAssignedLocals)
  171. {
  172. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  173. }
  174. }
  175. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  176. {
  177. BreakExtendChain();
  178. Validate();
  179. otherLocalAssignData.Validate();
  180. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  181. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  182. {
  183. if (!mAssignedLocals.Contains(*otherItr))
  184. mAssignedLocals.push_back(*otherItr);
  185. ++otherItr;
  186. }
  187. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  188. mLeftBlockUncond = mLeftBlockUncond || otherLocalAssignData.mLeftBlockUncond;
  189. }
  190. BfMethodState::~BfMethodState()
  191. {
  192. BF_ASSERT(mPendingNullConditional == NULL);
  193. if (mPrevMethodState != NULL)
  194. {
  195. BF_ASSERT(mCurAccessId == 1);
  196. BF_ASSERT(mCurLocalVarId <= 0);
  197. }
  198. for (auto local : mLocals)
  199. {
  200. if (local->mIsBumpAlloc)
  201. local->~BfLocalVariable();
  202. else
  203. delete local;
  204. }
  205. for (auto& kv : mLambdaCache)
  206. delete kv.mValue;
  207. }
  208. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  209. {
  210. auto checkMethodState = this;
  211. while (checkMethodState != NULL)
  212. {
  213. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  214. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  215. return checkMethodState;
  216. checkMethodState = checkMethodState->mPrevMethodState;
  217. }
  218. BF_FATAL("Failed to find method state for localvar");
  219. return NULL;
  220. }
  221. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx, BfLocalVarAssignKind assignKind, bool isFromDeferredAssignData)
  222. {
  223. auto localVarMethodState = GetMethodStateForLocal(localVar);
  224. if (localVarMethodState != this)
  225. {
  226. return;
  227. }
  228. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  229. {
  230. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  231. // 'a' is always defined, but 'b' isn't:
  232. // if (Check(out a) || Check(out b)) { } int z = a;
  233. auto deferredLocalAssignData = mDeferredLocalAssignData;
  234. if ((deferredLocalAssignData != NULL) &&
  235. (deferredLocalAssignData->mIsIfCondition) &&
  236. (!deferredLocalAssignData->mIfMayBeSkipped))
  237. {
  238. ifDeferredLocalAssignData = deferredLocalAssignData;
  239. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  240. }
  241. while ((deferredLocalAssignData != NULL) &&
  242. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  243. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  244. if (assignKind == BfLocalVarAssignKind_None)
  245. assignKind = ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mLeftBlock)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  246. if (localVar->mAssignedKind >= assignKind)
  247. {
  248. // Leave it alone
  249. }
  250. else if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  251. {
  252. if (fieldIdx >= 0)
  253. {
  254. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  255. if (localVar->mResolvedType->IsUnion())
  256. {
  257. // We need more 'smarts' to determine assignment of unions
  258. localVar->mUnassignedFieldFlags = 0;
  259. }
  260. if (localVar->mUnassignedFieldFlags == 0)
  261. {
  262. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  263. localVar->mAssignedKind = assignKind;
  264. }
  265. }
  266. else
  267. {
  268. localVar->mAssignedKind = assignKind;
  269. }
  270. }
  271. else
  272. {
  273. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  274. BfAssignedLocal defineVal = {localVar, fieldIdx, assignKind};
  275. if (!deferredLocalAssignData->Contains(defineVal))
  276. deferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  277. if (ifDeferredLocalAssignData != NULL)
  278. {
  279. if (!ifDeferredLocalAssignData->Contains(defineVal))
  280. ifDeferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  281. }
  282. }
  283. }
  284. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  285. }
  286. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  287. {
  288. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  289. if (deferredLocalAssignData.mLeftBlockUncond)
  290. {
  291. for (int localIdx = 0; localIdx < (int)mLocals.size(); localIdx++)
  292. {
  293. auto localDef = mLocals[localIdx];
  294. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  295. {
  296. bool hadAssignment = false;
  297. if (mDeferredLocalAssignData != NULL)
  298. {
  299. for (auto& entry : mDeferredLocalAssignData->mAssignedLocals)
  300. if (entry.mLocalVar == localDef)
  301. hadAssignment = true;
  302. }
  303. if (!hadAssignment)
  304. {
  305. LocalDefined(localDef);
  306. }
  307. }
  308. }
  309. }
  310. else
  311. {
  312. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  313. {
  314. LocalDefined(assignedLocal.mLocalVar, assignedLocal.mLocalVarField, assignedLocal.mAssignKind, true);
  315. }
  316. }
  317. }
  318. void BfMethodState::Reset()
  319. {
  320. mHeadScope.mDeferredCallEntries.DeleteAll();
  321. }
  322. //////////////////////////////////////////////////////////////////////////
  323. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  324. {
  325. Entry* entry = NULL;
  326. if (mEntries.TryAdd(id, NULL, &entry))
  327. {
  328. entry->mInterfaceEntry = interfaceEntry;
  329. entry->mMethodIdx = methodIdx;
  330. }
  331. if (!entry->mCandidates.Contains(candidateA))
  332. entry->mCandidates.push_back(candidateA);
  333. if (!entry->mCandidates.Contains(candidateB))
  334. entry->mCandidates.push_back(candidateB);
  335. }
  336. void BfAmbiguityContext::Remove(int id)
  337. {
  338. mEntries.Remove(id);
  339. }
  340. void BfAmbiguityContext::Finish()
  341. {
  342. for (auto& entryPair : mEntries)
  343. {
  344. int id = entryPair.mKey;
  345. auto entry = &entryPair.mValue;
  346. if (id >= 0)
  347. {
  348. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  349. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  350. if (error != NULL)
  351. {
  352. for (auto candidate : entry->mCandidates)
  353. {
  354. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  355. mModule->MethodToString(candidate, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType)).c_str()), candidate->mMethodDef->GetRefNode());
  356. }
  357. }
  358. }
  359. else
  360. {
  361. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  362. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  363. if (error != NULL)
  364. {
  365. for (auto candidate : entry->mCandidates)
  366. {
  367. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  368. mModule->MethodToString(candidate, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType)).c_str()), candidate->mMethodDef->GetRefNode());
  369. }
  370. }
  371. }
  372. }
  373. mEntries.Clear();
  374. }
  375. //////////////////////////////////////////////////////////////////////////
  376. class HasAppendAllocVisitor : BfElementVisitor
  377. {
  378. public:
  379. bool mHas;
  380. public:
  381. HasAppendAllocVisitor()
  382. {
  383. mHas = false;
  384. }
  385. void Visit(BfObjectCreateExpression* objCreateExpr)
  386. {
  387. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  388. {
  389. if (newToken->GetToken() == BfToken_Append)
  390. {
  391. mHas = true;
  392. }
  393. }
  394. }
  395. bool HasAppendAlloc(BfAstNode* node)
  396. {
  397. mHas = false;
  398. VisitChild(node);
  399. return mHas;
  400. }
  401. };
  402. class AppendAllocVisitor : public BfStructuralVisitor
  403. {
  404. public:
  405. BfModule* mModule;
  406. HasAppendAllocVisitor mHasAppendAllocVisitor;
  407. BfTypedValue mConstAccum;
  408. bool mFailed;
  409. bool mIsFirstConstPass;
  410. int mCurAppendAlign;
  411. public:
  412. AppendAllocVisitor()
  413. {
  414. mFailed = false;
  415. mIsFirstConstPass = false;
  416. mCurAppendAlign = 1;
  417. }
  418. void EmitAppendAlign(int align, int sizeMultiple = 0)
  419. {
  420. if (align <= 1)
  421. return;
  422. if (mIsFirstConstPass)
  423. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  424. if (sizeMultiple == 0)
  425. sizeMultiple = align;
  426. if (mCurAppendAlign == 0)
  427. mCurAppendAlign = sizeMultiple;
  428. else
  429. {
  430. if (sizeMultiple % align == 0)
  431. mCurAppendAlign = align;
  432. else
  433. mCurAppendAlign = sizeMultiple % align;
  434. }
  435. BF_ASSERT(mCurAppendAlign > 0);
  436. if (mConstAccum)
  437. {
  438. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  439. if (constant != NULL)
  440. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  441. else
  442. BF_ASSERT(mIsFirstConstPass);
  443. return;
  444. }
  445. mModule->EmitAppendAlign(align, sizeMultiple);
  446. }
  447. void Visit(BfAstNode* astNode) override
  448. {
  449. mModule->VisitChild(astNode);
  450. }
  451. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  452. {
  453. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  454. {
  455. if (newToken->GetToken() == BfToken_Append)
  456. {
  457. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  458. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  459. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  460. BfArrayType* arrayType = NULL;
  461. bool isArrayAlloc = false;
  462. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  463. SizedArray<BfIRValue, 2> dimLengthVals;
  464. BfType* origResolvedTypeRef = NULL;
  465. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  466. {
  467. if (variableDecl != NULL)
  468. {
  469. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  470. if (origResolvedTypeRef->IsObject())
  471. {
  472. if (origResolvedTypeRef->IsArray())
  473. {
  474. arrayType = (BfArrayType*)origResolvedTypeRef;
  475. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  476. isArrayAlloc = true;
  477. }
  478. }
  479. else if (origResolvedTypeRef->IsPointer())
  480. {
  481. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  482. }
  483. }
  484. }
  485. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  486. {
  487. isArrayAlloc = true;
  488. bool handled = false;
  489. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  490. {
  491. if (variableDecl->mTypeRef != NULL)
  492. {
  493. auto variableType = mModule->ResolveTypeRef(variableDecl->mTypeRef);
  494. if (variableType != NULL)
  495. {
  496. if (variableType->IsArray())
  497. origResolvedTypeRef = variableType->GetUnderlyingType();
  498. }
  499. handled = true;
  500. }
  501. }
  502. if (!handled)
  503. {
  504. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  505. }
  506. if (origResolvedTypeRef == NULL)
  507. {
  508. mModule->AssertErrorState();
  509. return;
  510. }
  511. int dimensions = 1;
  512. if (arrayTypeRef->mParams.size() != 0)
  513. {
  514. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  515. for (auto arg : arrayTypeRef->mParams)
  516. {
  517. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  518. {
  519. if (tokenNode->GetToken() == BfToken_Comma)
  520. {
  521. if (isRawArrayAlloc)
  522. {
  523. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  524. continue;
  525. }
  526. dimensions++;
  527. continue;
  528. }
  529. }
  530. auto expr = BfNodeDynCast<BfExpression>(arg);
  531. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  532. {
  533. mModule->CreateValueFromExpression(expr, intType);
  534. continue;
  535. }
  536. BfTypedValue dimLength;
  537. if (expr == NULL)
  538. {
  539. // Not specified
  540. dimLengthVals.push_back(BfIRValue());
  541. continue;
  542. }
  543. if (arg != NULL)
  544. dimLength = mModule->CreateValueFromExpression(expr, intType);
  545. if (!dimLength)
  546. {
  547. dimLength = mModule->GetDefaultTypedValue(intType);
  548. }
  549. dimLengthVals.push_back(dimLength.mValue);
  550. }
  551. }
  552. if (!isRawArrayAlloc)
  553. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  554. }
  555. if (origResolvedTypeRef == NULL)
  556. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  557. if (origResolvedTypeRef == NULL)
  558. {
  559. mModule->AssertErrorState();
  560. return;
  561. }
  562. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  563. auto resolvedTypeRef = origResolvedTypeRef;
  564. auto resultType = resolvedTypeRef;
  565. BfIRValue sizeValue;
  566. int curAlign = 0;
  567. if (isArrayAlloc)
  568. {
  569. int dimensions = 1;
  570. if (arrayType != NULL)
  571. dimensions = arrayType->mDimensions;
  572. bool sizeFailed = false;
  573. //
  574. {
  575. BfAstNode* initNode = objCreateExpr;
  576. for (int dim = 0; dim < dimensions; dim++)
  577. {
  578. BfAstNode* nextInitNode = NULL;
  579. int dimSize = -1;
  580. if (initNode == objCreateExpr)
  581. {
  582. dimSize = objCreateExpr->mArguments.size();
  583. if (!objCreateExpr->mArguments.IsEmpty())
  584. nextInitNode = objCreateExpr->mArguments[0];
  585. }
  586. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  587. {
  588. dimSize = (int)tupleNode->mCommas.size() + 1;
  589. }
  590. if (dimSize >= 0)
  591. {
  592. if (dim >= dimLengthVals.size())
  593. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  594. }
  595. else
  596. {
  597. sizeFailed = true;
  598. }
  599. }
  600. }
  601. BfIRValue allocCount;
  602. if (!sizeFailed)
  603. {
  604. if (!dimLengthVals.IsEmpty())
  605. {
  606. allocCount = dimLengthVals[0];
  607. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  608. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  609. }
  610. }
  611. if (!allocCount)
  612. {
  613. mFailed = true;
  614. if (!mIsFirstConstPass)
  615. {
  616. if (!mConstAccum)
  617. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  618. return;
  619. }
  620. }
  621. mModule->PopulateType(resultType);
  622. if (isRawArrayAlloc)
  623. {
  624. curAlign = resultType->mAlign;
  625. EmitAppendAlign(resultType->mAlign);
  626. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  627. }
  628. else
  629. {
  630. if (arrayType == NULL)
  631. arrayType = mModule->CreateArrayType(resultType, 1);
  632. // Array is a special case where the total size isn't aligned with mAlign
  633. // since we add arbitrary elements to the end without padding the end to align
  634. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  635. curAlign = arrayType->mAlign;
  636. auto firstElementField = &arrayType->mFieldInstances.back();
  637. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  638. sizeValue = mModule->GetConstValue(arrayClassSize);
  639. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  640. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  641. }
  642. }
  643. else
  644. {
  645. auto typeInst = resultType->ToTypeInstance();
  646. if (typeInst != NULL)
  647. {
  648. curAlign = typeInst->mInstAlign;
  649. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  650. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  651. }
  652. else
  653. {
  654. curAlign = resultType->mAlign;
  655. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  656. sizeValue = mModule->GetConstValue(resultType->mSize);
  657. }
  658. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  659. BfExprEvaluator exprEvaluator(mModule);
  660. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  661. BfFunctionBindResult bindResult;
  662. bindResult.mWantsArgs = true;
  663. exprEvaluator.mFunctionBindResult = &bindResult;
  664. SizedArray<BfExpression*, 8> copiedArgs;
  665. for (BfExpression* arg : objCreateExpr->mArguments)
  666. copiedArgs.push_back(arg);
  667. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  668. BfResolvedArgs argValues(&sizedArgExprs);
  669. if (typeInst != NULL)
  670. {
  671. exprEvaluator.ResolveArgValues(argValues);
  672. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  673. }
  674. exprEvaluator.mFunctionBindResult = NULL;
  675. if (bindResult.mMethodInstance != NULL)
  676. {
  677. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  678. {
  679. auto calcAppendArgs = bindResult.mIRArgs;
  680. BF_ASSERT(calcAppendArgs[0].IsFake());
  681. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  682. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  683. auto subDependSize = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, calcAppendArgs);
  684. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  685. {
  686. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  687. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  688. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  689. }
  690. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  691. if ((!subDependSize) && (!mConstAccum))
  692. {
  693. BF_ASSERT(calcAppendMethodModule.mFunc);
  694. subDependSize = exprEvaluator.CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  695. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  696. }
  697. if (subDependSize)
  698. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  699. else
  700. mFailed = true;
  701. }
  702. }
  703. }
  704. if (sizeValue)
  705. {
  706. if (mConstAccum)
  707. {
  708. if (!sizeValue.IsConst())
  709. {
  710. mFailed = true;
  711. if (!mIsFirstConstPass)
  712. return;
  713. }
  714. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  715. }
  716. else
  717. {
  718. auto prevVal = mModule->mBfIRBuilder->CreateAlignedLoad(accumValuePtr, intPtrType->mAlign);
  719. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  720. mModule->mBfIRBuilder->CreateAlignedStore(addedVal, accumValuePtr, intPtrType->mAlign);
  721. }
  722. }
  723. }
  724. }
  725. }
  726. void Visit(BfObjectCreateExpression* objCreateExpr) override
  727. {
  728. DoObjectCreate(objCreateExpr, NULL);
  729. }
  730. void Visit(BfVariableDeclaration* varDecl) override
  731. {
  732. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  733. {
  734. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  735. DoObjectCreate(objectCreateExpr, varDecl);
  736. else
  737. VisitChild(varDecl->mInitializer);
  738. if (varDecl->mNameNode != NULL)
  739. {
  740. BfLocalVariable* localDef = new BfLocalVariable();
  741. localDef->mName = varDecl->mNameNode->ToString();
  742. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  743. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  744. localDef->mIsReadOnly = true;
  745. localDef->mParamFailed = true;
  746. localDef->mReadFromId = 0;
  747. mModule->AddLocalVariableDef(localDef);
  748. }
  749. }
  750. else
  751. {
  752. mModule->Visit(varDecl);
  753. }
  754. }
  755. void Visit(BfExpressionStatement* exprStatement) override
  756. {
  757. VisitChild(exprStatement->mExpression);
  758. }
  759. // void Visit(BfIfStatement* ifStmt) override
  760. // {
  761. // mModule->DoIfStatement(ifStmt,
  762. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  763. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  764. // }
  765. void Visit(BfBlock* block) override
  766. {
  767. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  768. return;
  769. int appendAllocIdx = -1;
  770. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  771. {
  772. auto child = block->mChildArr.mVals[childIdx];
  773. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  774. {
  775. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  776. {
  777. auto emitChild = block->mChildArr.mVals[emitIdx];
  778. mModule->UpdateSrcPos(emitChild);
  779. VisitChild(emitChild);
  780. if ((mFailed) && (!mIsFirstConstPass))
  781. break;
  782. }
  783. break;
  784. }
  785. }
  786. }
  787. };
  788. //////////////////////////////////////////////////////////////////////////
  789. BfModule* gLastCreatedModule = NULL;
  790. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  791. {
  792. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  793. gLastCreatedModule = this;
  794. mContext = context;
  795. mModuleName = moduleName;
  796. if (!moduleName.empty())
  797. {
  798. StringT<256> upperModuleName = moduleName;
  799. MakeUpper(upperModuleName);
  800. mContext->mUsedModuleNames.Add(upperModuleName);
  801. }
  802. mAddedToCount = false;
  803. mParentModule = NULL;
  804. mNextAltModule = NULL;
  805. mBfIRBuilder = NULL;
  806. mWantsIRIgnoreWrites = false;
  807. mModuleOptions = NULL;
  808. mLastUsedRevision = -1;
  809. mUsedSlotCount = -1;
  810. mIsReified = true;
  811. mGeneratesCode = true;
  812. mReifyQueued = false;
  813. mIsSpecialModule = false;
  814. mIsComptimeModule = false;
  815. mIsScratchModule = false;
  816. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  817. mHadBuildError = false;
  818. mHadBuildWarning = false;
  819. mIgnoreErrors = false;
  820. mHadIgnoredError = false;
  821. mIgnoreWarnings = false;
  822. mReportErrors = true;
  823. mIsInsideAutoComplete = false;
  824. mIsDeleting = false;
  825. mSkipInnerLookup = false;
  826. mIsHotModule = false;
  827. mSetIllegalSrcPosition = false;
  828. mNoResolveGenericParams = false;
  829. mWroteToLib = false;
  830. mContext = context;
  831. mCompiler = context->mCompiler;
  832. mSystem = mCompiler->mSystem;
  833. mProject = NULL;
  834. mCurMethodState = NULL;
  835. mAttributeState = NULL;
  836. mCurLocalMethodId = 0;
  837. mParentNodeEntry = NULL;
  838. mRevision = -1;
  839. mRebuildIdx = 0;
  840. mLastModuleWrittenRevision = 0;
  841. mIsModuleMutable = false;
  842. mExtensionCount = 0;
  843. mIncompleteMethodCount = 0;
  844. mOnDemandMethodCount = 0;
  845. mHasGenericMethods = false;
  846. mCurMethodInstance = NULL;
  847. mCurTypeInstance = NULL;
  848. mAwaitingInitFinish = false;
  849. mAwaitingFinish = false;
  850. mHasFullDebugInfo = false;
  851. mHadHotObjectWrites = false;
  852. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  853. mBuiltInFuncs[i] = BfIRFunction();
  854. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  855. }
  856. void BfReportMemory();
  857. BfModule::~BfModule()
  858. {
  859. mRevision = -2;
  860. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  861. if (!mIsDeleting)
  862. RemoveModuleData();
  863. }
  864. void BfModule::RemoveModuleData()
  865. {
  866. BF_ASSERT(!mIsDeleting);
  867. if (!mModuleName.empty())
  868. {
  869. // Note: module names not necessarily unique
  870. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  871. }
  872. CleanupFileInstances();
  873. delete mBfIRBuilder;
  874. mBfIRBuilder = NULL;
  875. //delete mCpu;
  876. for (auto prevModule : mPrevIRBuilders)
  877. delete prevModule;
  878. mPrevIRBuilders.Clear();
  879. for (auto& pairVal : mDeferredMethodCallData)
  880. delete pairVal.mValue;
  881. mDeferredMethodCallData.Clear();
  882. mDeferredMethodIds.Clear();
  883. for (auto& specModulePair : mSpecializedMethodModules)
  884. delete specModulePair.mValue;
  885. mSpecializedMethodModules.Clear();
  886. if (mNextAltModule != NULL)
  887. delete mNextAltModule;
  888. mNextAltModule = NULL;
  889. if (mModuleOptions != NULL)
  890. delete mModuleOptions;
  891. mModuleOptions = NULL;
  892. BfReportMemory();
  893. }
  894. void BfModule::Init(bool isFullRebuild)
  895. {
  896. mContext->mFinishedModuleWorkList.Remove(this);
  897. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  898. BF_ASSERT(mIsReified);
  899. if (!mIsScratchModule)
  900. {
  901. mCompiler->mStats.mModulesStarted++;
  902. if (mIsReified)
  903. mCompiler->mStats.mReifiedModuleCount++;
  904. mAddedToCount = true;
  905. }
  906. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  907. mFuncReferences.Clear();
  908. mClassVDataRefs.Clear();
  909. mClassVDataExtRefs.Clear();
  910. //mTypeDataRefs.Clear();
  911. mDbgRawAllocDataRefs.Clear();
  912. CleanupFileInstances();
  913. mStaticFieldRefs.Clear();
  914. //mInterfaceSlotRefs.Clear();
  915. // If we are just doing an extension then the ownede types aren't rebuilt.
  916. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  917. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  918. if (isFullRebuild)
  919. mRevision = mCompiler->mRevision;
  920. BF_ASSERT(mCurTypeInstance == NULL);
  921. mIsModuleMutable = true;
  922. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  923. if (!mIsComptimeModule)
  924. {
  925. #ifdef _DEBUG
  926. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  927. #else
  928. EnsureIRBuilder(false);
  929. #endif
  930. }
  931. mCurMethodState = NULL;
  932. mAwaitingInitFinish = true;
  933. mOnDemandMethodCount = 0;
  934. mAwaitingFinish = false;
  935. mHasForceLinkMarker = false;
  936. mUsedSlotCount = -1;
  937. }
  938. bool BfModule::WantsFinishModule()
  939. {
  940. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  941. }
  942. bool BfModule::IsHotCompile()
  943. {
  944. return mCompiler->IsHotCompile() && !mIsComptimeModule;
  945. }
  946. void BfModule::FinishInit()
  947. {
  948. BF_ASSERT(mAwaitingInitFinish);
  949. auto moduleOptions = GetModuleOptions();
  950. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  951. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple, mCompiler->mOptions.mTargetCPU);
  952. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  953. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  954. {
  955. // Og+ requires debug info
  956. moduleOptions.mEmitDebugInfo = 1;
  957. }
  958. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  959. if (mIsComptimeModule)
  960. mHasFullDebugInfo = true;
  961. if (((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified)) ||
  962. (mIsComptimeModule))
  963. {
  964. mBfIRBuilder->DbgInit();
  965. }
  966. else
  967. mHasFullDebugInfo = false;
  968. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  969. ((moduleOptions.mEmitDebugInfo != 0)))
  970. {
  971. if (mCompiler->mOptions.IsCodeView())
  972. {
  973. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  974. }
  975. else
  976. {
  977. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  978. }
  979. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  980. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  981. }
  982. mAwaitingInitFinish = false;
  983. }
  984. void BfModule::CalcGeneratesCode()
  985. {
  986. if ((!mIsReified) || (mIsScratchModule))
  987. {
  988. mGeneratesCode = false;
  989. return;
  990. }
  991. mGeneratesCode = false;
  992. for (auto typeInst : mOwnedTypeInstances)
  993. if (!typeInst->IsInterface())
  994. mGeneratesCode = true;
  995. }
  996. void BfModule::ReifyModule()
  997. {
  998. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  999. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  1000. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  1001. mIsReified = true;
  1002. CalcGeneratesCode();
  1003. mReifyQueued = false;
  1004. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  1005. mCompiler->mStats.mModulesReified++;
  1006. }
  1007. void BfModule::UnreifyModule()
  1008. {
  1009. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  1010. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  1011. mIsReified = false;
  1012. CalcGeneratesCode();
  1013. mReifyQueued = false;
  1014. StartNewRevision(RebuildKind_None, true);
  1015. mCompiler->mStats.mModulesUnreified++;
  1016. }
  1017. void BfModule::CleanupFileInstances()
  1018. {
  1019. for (auto& itr : mNamedFileInstanceMap)
  1020. {
  1021. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  1022. delete itr.mValue;
  1023. }
  1024. mCurFilePosition.mFileInstance = NULL;//
  1025. mFileInstanceMap.Clear();
  1026. mNamedFileInstanceMap.Clear();
  1027. }
  1028. void BfModule::Cleanup()
  1029. {
  1030. CleanupFileInstances();
  1031. }
  1032. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  1033. {
  1034. if (HasCompiledOutput())
  1035. {
  1036. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  1037. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  1038. {
  1039. StartExtension();
  1040. }
  1041. }
  1042. else
  1043. {
  1044. EnsureIRBuilder();
  1045. }
  1046. }
  1047. void BfModule::SetupIRBuilder(bool dbgVerifyCodeGen)
  1048. {
  1049. if (mIsScratchModule)
  1050. {
  1051. mBfIRBuilder->mIgnoreWrites = true;
  1052. BF_ASSERT(!dbgVerifyCodeGen);
  1053. }
  1054. #ifdef _DEBUG
  1055. if (mCompiler->mIsResolveOnly)
  1056. {
  1057. // For "deep" verification testing
  1058. /*if (!mIsSpecialModule)
  1059. dbgVerifyCodeGen = true;*/
  1060. // We only want to turn this off on smaller builds for testing
  1061. mBfIRBuilder->mIgnoreWrites = true;
  1062. if (dbgVerifyCodeGen)
  1063. mBfIRBuilder->mIgnoreWrites = false;
  1064. if (!mBfIRBuilder->mIgnoreWrites)
  1065. {
  1066. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  1067. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1068. }
  1069. }
  1070. else if (!mGeneratesCode)
  1071. {
  1072. mBfIRBuilder->mIgnoreWrites = true;
  1073. }
  1074. else
  1075. {
  1076. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  1077. // code as we walk the AST
  1078. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1079. if (
  1080. (mModuleName == "-")
  1081. //|| (mModuleName == "BeefTest2_ClearColorValue")
  1082. //|| (mModuleName == "Tests_FuncRefs")
  1083. )
  1084. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1085. // Just for testing!
  1086. //mBfIRBuilder->mIgnoreWrites = true;
  1087. }
  1088. #else
  1089. if (mCompiler->mIsResolveOnly)
  1090. {
  1091. // Always ignore writes in resolveOnly for release builds
  1092. mBfIRBuilder->mIgnoreWrites = true;
  1093. }
  1094. else
  1095. {
  1096. // Just for memory testing! This breaks everything.
  1097. //mBfIRBuilder->mIgnoreWrites = true;
  1098. // For "deep" verification testing
  1099. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1100. }
  1101. #endif
  1102. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  1103. }
  1104. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  1105. {
  1106. BF_ASSERT(!mIsDeleting);
  1107. if (mBfIRBuilder == NULL)
  1108. {
  1109. if ((!mIsScratchModule) && (!mAddedToCount))
  1110. {
  1111. mCompiler->mStats.mModulesStarted++;
  1112. mAddedToCount = true;
  1113. }
  1114. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  1115. /*if (mCompiler->mIsResolveOnly)
  1116. BF_ASSERT(mIsResolveOnly);*/
  1117. mBfIRBuilder = new BfIRBuilder(this);
  1118. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  1119. SetupIRBuilder(dbgVerifyCodeGen);
  1120. }
  1121. }
  1122. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1123. {
  1124. String name = "FORCELINKMOD_" + module->mModuleName;
  1125. if (outName != NULL)
  1126. *outName = name;
  1127. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1128. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1129. }
  1130. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1131. {
  1132. BP_ZONE("BfModule::StartNewRevision");
  1133. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1134. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1135. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1136. if (mCompiler->mCompileState == BfCompiler::CompileState_Cleanup)
  1137. {
  1138. // Cleaning up local methods may cause some necessary NewRevisions
  1139. force = true;
  1140. }
  1141. // Already on new revision?
  1142. if ((mRevision == mCompiler->mRevision) && (!force))
  1143. return;
  1144. mHadBuildError = false;
  1145. mHadBuildWarning = false;
  1146. mExtensionCount = 0;
  1147. mRevision = mCompiler->mRevision;
  1148. mRebuildIdx++;
  1149. ClearModuleData(!force);
  1150. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1151. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1152. {
  1153. mStringPoolRefs.Clear();
  1154. mUnreifiedStringPoolRefs.Clear();
  1155. }
  1156. mDllImportEntries.Clear();
  1157. mImportFileNames.Clear();
  1158. for (auto& pairVal : mDeferredMethodCallData)
  1159. delete pairVal.mValue;
  1160. mDeferredMethodCallData.Clear();
  1161. mDeferredMethodIds.Clear();
  1162. mModuleRefs.Clear();
  1163. mOutFileNames.Clear();
  1164. mTypeDataRefs.Clear();
  1165. mInterfaceSlotRefs.Clear();
  1166. if (rebuildKind == BfModule::RebuildKind_None)
  1167. {
  1168. for (auto& specPair : mSpecializedMethodModules)
  1169. {
  1170. auto specModule = specPair.mValue;
  1171. if (specModule->mIsReified != mIsReified)
  1172. {
  1173. if (mIsReified)
  1174. specModule->ReifyModule();
  1175. else
  1176. specModule->UnreifyModule();
  1177. }
  1178. }
  1179. }
  1180. else
  1181. {
  1182. for (auto& specPair : mSpecializedMethodModules)
  1183. {
  1184. auto specModule = specPair.mValue;
  1185. BfLogSysM("Setting module mIsDeleting %p due to parent module starting a new revision\n", specModule);
  1186. // This module is no longer needed
  1187. specModule->RemoveModuleData();
  1188. specModule->mIsDeleting = true;
  1189. mContext->mDeletingModules.Add(specModule);
  1190. }
  1191. }
  1192. mSpecializedMethodModules.Clear();
  1193. delete mNextAltModule;
  1194. mNextAltModule = NULL;
  1195. BF_ASSERT(mModuleOptions == NULL);
  1196. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1197. bool needsTypePopulated = false;
  1198. int oldOnDemandCount = 0;
  1199. // We don't have to rebuild types in the unspecialized module because there is no
  1200. // data that's needed -- their method instances are all NULL and the module
  1201. // doesn't get included in the build
  1202. if (this != mContext->mScratchModule)
  1203. {
  1204. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1205. {
  1206. auto typeInst = mOwnedTypeInstances[typeIdx];
  1207. if (!typeInst->IsDeleting())
  1208. {
  1209. typeInst->mIsReified = mIsReified;
  1210. if (rebuildKind != BfModule::RebuildKind_None)
  1211. {
  1212. if (typeInst->IsOnDemand())
  1213. {
  1214. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1215. if (rebuildKind == BfModule::RebuildKind_All)
  1216. mContext->DeleteType(typeInst);
  1217. else
  1218. {
  1219. RebuildMethods(typeInst);
  1220. }
  1221. }
  1222. else
  1223. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1224. mContext->RebuildType(typeInst, false, false, true);
  1225. //mContext->RebuildType(typeInst, false, false, false);
  1226. }
  1227. else
  1228. {
  1229. auto _HandleMethod = [&](BfMethodInstance* methodInstance)
  1230. {
  1231. if ((methodInstance != NULL) && (methodInstance->mDeclModule != NULL))
  1232. methodInstance->mDeclModule = this;
  1233. };
  1234. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1235. {
  1236. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1237. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  1238. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  1239. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  1240. {
  1241. oldOnDemandCount++;
  1242. }
  1243. _HandleMethod(methodGroup.mDefault);
  1244. if (methodGroup.mMethodSpecializationMap != NULL)
  1245. for (auto& kv : *methodGroup.mMethodSpecializationMap)
  1246. _HandleMethod(kv.mValue);
  1247. }
  1248. }
  1249. if (typeInst->IsDeleting())
  1250. typeIdx--;
  1251. }
  1252. }
  1253. }
  1254. if (!mIsDeleting)
  1255. Init();
  1256. mOnDemandMethodCount += oldOnDemandCount;
  1257. VerifyOnDemandMethods();
  1258. }
  1259. void BfModule::StartExtension()
  1260. {
  1261. BF_ASSERT(!mIsModuleMutable);
  1262. BfLogSysM("Extension started of module %p\n", this);
  1263. mExtensionCount++;
  1264. if (mBfIRBuilder != NULL)
  1265. mPrevIRBuilders.push_back(mBfIRBuilder);
  1266. mBfIRBuilder = NULL;
  1267. mWantsIRIgnoreWrites = false;
  1268. mFuncReferences.Clear();
  1269. mClassVDataRefs.Clear();
  1270. mClassVDataExtRefs.Clear();
  1271. for (auto& kv : mTypeDataRefs)
  1272. kv.mValue = BfIRValue();
  1273. mDbgRawAllocDataRefs.Clear();
  1274. mStringCharPtrPool.Clear();
  1275. mStringObjectPool.Clear();
  1276. mStaticFieldRefs.Clear();
  1277. for (auto& kv : mInterfaceSlotRefs)
  1278. kv.mValue = BfIRValue();
  1279. for (auto& pairVal : mDeferredMethodCallData)
  1280. delete pairVal.mValue;
  1281. mDeferredMethodCallData.Clear();
  1282. mDeferredMethodIds.Clear();
  1283. DisownMethods();
  1284. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1285. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1286. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1287. Init(false);
  1288. if (!wasAwaitingInitFinish)
  1289. FinishInit();
  1290. mOnDemandMethodCount = prevOnDemandMethodCount;
  1291. }
  1292. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1293. {
  1294. auto hasObjectDebugFlags = mContext->mBfObjectType->mFieldInstances[0].mResolvedType->IsInteger();
  1295. BfIRValue vDataValue;
  1296. if (hasObjectDebugFlags)
  1297. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1298. else
  1299. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1300. typeValueParams.push_back(vDataValue);
  1301. if (hasObjectDebugFlags)
  1302. {
  1303. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1304. typeValueParams.push_back(GetDefaultValue(primType));
  1305. }
  1306. }
  1307. BfIRValue BfModule::GetConstValue(int64 val)
  1308. {
  1309. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1310. }
  1311. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1312. {
  1313. BfType* checkType = type;
  1314. if (type->IsTypedPrimitive())
  1315. {
  1316. checkType = type->GetUnderlyingType();
  1317. }
  1318. if (checkType->IsPrimitiveType())
  1319. {
  1320. auto primType = (BfPrimitiveType*)checkType;
  1321. if (checkType->IsFloat())
  1322. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1323. else
  1324. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1325. }
  1326. return BfIRValue();
  1327. }
  1328. BfIRValue BfModule::GetConstValue8(int val)
  1329. {
  1330. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1331. }
  1332. BfIRValue BfModule::GetConstValue32(int32 val)
  1333. {
  1334. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1335. }
  1336. BfIRValue BfModule::GetConstValue64(int64 val)
  1337. {
  1338. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1339. }
  1340. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1341. {
  1342. PopulateType(type, BfPopulateType_Data);
  1343. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1344. if (type->IsTypedPrimitive())
  1345. {
  1346. auto underlyingType = type->GetUnderlyingType();
  1347. if (underlyingType == NULL)
  1348. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1349. return GetDefaultValue(type->GetUnderlyingType());
  1350. }
  1351. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1352. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1353. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1354. if ((type->IsIntegral()) || (type->IsBoolean()))
  1355. {
  1356. auto primType = (BfPrimitiveType*)type;
  1357. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1358. }
  1359. if (type->IsFloat())
  1360. {
  1361. auto primType = (BfPrimitiveType*)type;
  1362. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1363. }
  1364. return mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(type));
  1365. }
  1366. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1367. {
  1368. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1369. if (type->mSize == 0)
  1370. return BfTypedValue(BfIRValue::sValueless, type);
  1371. else if (mBfIRBuilder != NULL)
  1372. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1373. else
  1374. return BfTypedValue(BfIRValue(BfIRValueFlags_Value, -1), type);
  1375. }
  1376. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1377. {
  1378. if (type->IsVar())
  1379. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1380. PopulateType(type, BfPopulateType_Data);
  1381. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1382. if (defaultValueKind == BfDefaultValueKind_Undef)
  1383. {
  1384. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(type)), type);
  1385. }
  1386. BfTypedValue typedValue;
  1387. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1388. {
  1389. if (type->IsRef())
  1390. {
  1391. BfRefType* refType = (BfRefType*)type;
  1392. BfType* underlyingType = refType->GetUnderlyingType();
  1393. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1394. }
  1395. else
  1396. {
  1397. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1398. }
  1399. if (!mBfIRBuilder->mIgnoreWrites)
  1400. {
  1401. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1402. GetConstValue(type->mSize), type->mAlign);
  1403. }
  1404. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1405. typedValue = LoadValue(typedValue);
  1406. return typedValue;
  1407. }
  1408. if ((type->IsRef()) && (!allowRef))
  1409. {
  1410. BfRefType* refType = (BfRefType*)type;
  1411. BfType* underlyingType = refType->GetUnderlyingType();
  1412. if (underlyingType->IsValuelessType())
  1413. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1414. else
  1415. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1416. }
  1417. else
  1418. {
  1419. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1420. }
  1421. return typedValue;
  1422. }
  1423. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1424. {
  1425. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1426. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1427. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1428. BfIRValue strConstant;
  1429. if (define)
  1430. {
  1431. strConstant = mBfIRBuilder->CreateConstString(str);
  1432. }
  1433. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1434. true, BfIRLinkageType_External,
  1435. strConstant, stringDataName);
  1436. if (define)
  1437. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1438. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1439. }
  1440. void BfModule::FixConstValueParams(BfTypeInstance* typeInst, SizedArrayImpl<BfIRValue>& valueParams, bool fillInPadding)
  1441. {
  1442. if ((!typeInst->mTypeDef->mIsCombinedPartial) && (!fillInPadding))
  1443. return;
  1444. int prevDataIdx = -1;
  1445. int usedDataIdx = 0;
  1446. int valueParamIdx = 0;
  1447. if (typeInst->mBaseType != NULL)
  1448. {
  1449. usedDataIdx++;
  1450. valueParamIdx++;
  1451. prevDataIdx++;
  1452. }
  1453. int startingParamsSize = (int)valueParams.mSize;
  1454. for (int fieldIdx = 0; fieldIdx < (int)typeInst->mFieldInstances.size(); fieldIdx++)
  1455. {
  1456. auto fieldInstance = &typeInst->mFieldInstances[fieldIdx];
  1457. if (fieldInstance->mDataIdx < 0)
  1458. continue;
  1459. BF_ASSERT(fieldInstance->mDataIdx > prevDataIdx);
  1460. if (fillInPadding)
  1461. {
  1462. for (int i = prevDataIdx + 1; i < fieldInstance->mDataIdx; i++)
  1463. valueParams.Insert(valueParamIdx++, mBfIRBuilder->CreateConstArrayZero(0));
  1464. }
  1465. valueParamIdx++;
  1466. prevDataIdx = fieldInstance->mDataIdx;
  1467. usedDataIdx++;
  1468. if (usedDataIdx <= valueParams.mSize)
  1469. continue;
  1470. valueParams.Add(GetDefaultValue(fieldInstance->mResolvedType));
  1471. }
  1472. }
  1473. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1474. {
  1475. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1476. mBfIRBuilder->PopulateType(stringTypeInst);
  1477. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1478. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1479. BfIRValue stringValData;
  1480. if (define)
  1481. {
  1482. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1483. mStringCharPtrPool[stringId] = stringCharsVal;
  1484. SizedArray<BfIRValue, 8> typeValueParams;
  1485. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1486. FixConstValueParams(stringTypeInst->mBaseType, typeValueParams);
  1487. auto objData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1488. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1489. typeValueParams.clear();
  1490. typeValueParams.push_back(objData);
  1491. if (lenByteCount == 4)
  1492. {
  1493. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1494. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1495. }
  1496. else
  1497. {
  1498. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1499. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1500. }
  1501. typeValueParams.push_back(stringCharsVal); // mPtr
  1502. FixConstValueParams(stringTypeInst, typeValueParams);
  1503. stringValData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1504. }
  1505. mBfIRBuilder->PopulateType(stringTypeInst);
  1506. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1507. mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full),
  1508. true,
  1509. BfIRLinkageType_External,
  1510. define ? stringValData : BfIRValue(),
  1511. stringObjName);
  1512. return stringValLiteral;
  1513. }
  1514. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1515. {
  1516. if (constHolder == NULL)
  1517. constHolder = mBfIRBuilder;
  1518. auto constant = constHolder->GetConstant(constantStr);
  1519. if (constant == NULL)
  1520. return -1;
  1521. if (constant->mTypeCode == BfTypeCode_StringId)
  1522. {
  1523. return constant->mInt32;
  1524. }
  1525. while (constant->mConstType == BfConstType_BitCast)
  1526. {
  1527. auto constBitCast = (BfConstantBitCast*)constant;
  1528. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1529. }
  1530. if (constant->mConstType == BfConstType_GEP32_2)
  1531. {
  1532. auto constGEP = (BfConstantGEP32_2*)constant;
  1533. constant = constHolder->GetConstantById(constGEP->mTarget);
  1534. }
  1535. if (constant->mConstType == BfConstType_GlobalVar)
  1536. {
  1537. auto constGV = (BfGlobalVar*)constant;
  1538. const char* strDataPrefix = "__bfStrData";
  1539. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1540. return atoi(constGV->mName + strlen(strDataPrefix));
  1541. const char* strObjPrefix = "__bfStrObj";
  1542. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1543. return atoi(constGV->mName + strlen(strObjPrefix));
  1544. }
  1545. return -1;
  1546. }
  1547. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1548. {
  1549. int strId = GetStringPoolIdx(constantStr, constHolder);
  1550. if (strId != -1)
  1551. {
  1552. auto& entry = mContext->mStringObjectIdMap[strId];
  1553. return &entry.mString;
  1554. }
  1555. return NULL;
  1556. }
  1557. CeDbgState* BfModule::GetCeDbgState()
  1558. {
  1559. if (!mIsComptimeModule)
  1560. return NULL;
  1561. if ((mCompiler->mCeMachine != NULL) && (mCompiler->mCeMachine->mDebugger != NULL))
  1562. return mCompiler->mCeMachine->mDebugger->mCurDbgState;
  1563. return NULL;
  1564. }
  1565. BfIRValue BfModule::GetStringCharPtr(int stringId, bool force)
  1566. {
  1567. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1568. {
  1569. mUnreifiedStringPoolRefs.Add(stringId);
  1570. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, stringId);
  1571. }
  1572. BfIRValue* irValue = NULL;
  1573. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1574. return *irValue;
  1575. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1576. if (!mStringObjectPool.ContainsKey(stringId))
  1577. mStringPoolRefs.Add(stringId);
  1578. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1579. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1580. *irValue = strCharPtrConst;
  1581. return strCharPtrConst;
  1582. }
  1583. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue, bool force)
  1584. {
  1585. if (strValue.IsConst())
  1586. {
  1587. int stringId = GetStringPoolIdx(strValue);
  1588. BF_ASSERT(stringId != -1);
  1589. return GetStringCharPtr(stringId, force);
  1590. }
  1591. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1592. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1593. return charPtr;
  1594. }
  1595. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str, bool force)
  1596. {
  1597. return GetStringCharPtr(GetStringObjectValue(str, force), force);
  1598. }
  1599. BfIRValue BfModule::GetStringObjectValue(int strId, bool define, bool force)
  1600. {
  1601. BfIRValue* objValue;
  1602. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1603. return *objValue;
  1604. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1605. return GetStringObjectValue(stringPoolEntry.mString, define, force);
  1606. }
  1607. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define, bool force)
  1608. {
  1609. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1610. mBfIRBuilder->PopulateType(stringType);
  1611. int strId = mContext->GetStringLiteralId(str);
  1612. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1613. {
  1614. auto refModule = this;
  1615. if ((this == mContext->mUnreifiedModule) && (mCurTypeInstance != NULL))
  1616. refModule = mCurTypeInstance->mModule;
  1617. refModule->mUnreifiedStringPoolRefs.Add(strId);
  1618. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, strId);
  1619. }
  1620. BfIRValue* irValuePtr = NULL;
  1621. if (mStringObjectPool.TryGetValue(strId, &irValuePtr))
  1622. return *irValuePtr;
  1623. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1624. if (!mStringCharPtrPool.ContainsKey(strId))
  1625. mStringPoolRefs.Add(strId);
  1626. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1627. mStringObjectPool[strId] = strObject;
  1628. mStringPoolRefs.Add(strId);
  1629. return strObject;
  1630. }
  1631. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1632. {
  1633. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1634. type,
  1635. true,
  1636. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1637. constant,
  1638. name.c_str());
  1639. return newConst;
  1640. }
  1641. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1642. {
  1643. auto curScope = mCurMethodState->mCurScope;
  1644. if (curScope->mLabelNode != NULL)
  1645. {
  1646. curScope->mLabelNode->ToString(curScope->mLabel);
  1647. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1648. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1649. auto autoComplete = mCompiler->GetAutoComplete();
  1650. if (autoComplete != NULL)
  1651. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1652. }
  1653. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1654. {
  1655. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1656. while (checkScope != NULL)
  1657. {
  1658. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1659. {
  1660. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1661. if (errorNode != NULL)
  1662. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1663. break;
  1664. }
  1665. checkScope = checkScope->mPrevScope;
  1666. }
  1667. }
  1668. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1669. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1670. {
  1671. if (prevScope->mHadScopeValueRetain)
  1672. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1673. else
  1674. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1675. }
  1676. mCurMethodState->mBlockNestLevel++;
  1677. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1678. {
  1679. // DIScope could be NULL if we're in an unspecialized method (for example)
  1680. if (mCurMethodState->mCurScope->mDIScope)
  1681. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1682. }
  1683. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1684. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1685. mCurMethodState->mCurScope->mMixinState = mCurMethodState->mMixinState;
  1686. }
  1687. void BfModule::RestoreScoreState_LocalVariables(int localVarStart)
  1688. {
  1689. while (localVarStart < (int)mCurMethodState->mLocals.size())
  1690. {
  1691. auto localVar = mCurMethodState->mLocals.back();
  1692. LocalVariableDone(localVar, false);
  1693. mCurMethodState->mLocals.pop_back();
  1694. if (localVar->mShadowedLocal != NULL)
  1695. {
  1696. BfLocalVarEntry* localVarEntryPtr;
  1697. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1698. {
  1699. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1700. }
  1701. }
  1702. else
  1703. {
  1704. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1705. }
  1706. if (localVar->mIsBumpAlloc)
  1707. localVar->~BfLocalVariable();
  1708. else
  1709. delete localVar;
  1710. }
  1711. }
  1712. void BfModule::RestoreScopeState()
  1713. {
  1714. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1715. mCurMethodState->mBlockNestLevel--;
  1716. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1717. {
  1718. BfIRBlock afterEndBlock;
  1719. if (!mCurMethodState->mLeftBlockUncond)
  1720. {
  1721. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1722. mBfIRBuilder->CreateBr(afterEndBlock);
  1723. mBfIRBuilder->ClearDebugLocation_Last();
  1724. }
  1725. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1726. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1727. if (afterEndBlock)
  1728. {
  1729. mBfIRBuilder->AddBlock(afterEndBlock);
  1730. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1731. }
  1732. }
  1733. mCurMethodState->mCurScope->mDone = true;
  1734. if (!mCurMethodState->mLeftBlockUncond)
  1735. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1736. EmitDeferredCallProcessorInstances(mCurMethodState->mCurScope);
  1737. RestoreScoreState_LocalVariables(mCurMethodState->mCurScope->mLocalVarStart);
  1738. if (mCurMethodState->mCurScope->mValueScopeStart)
  1739. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1740. mCurMethodState->mCurScope = prevScopeData;
  1741. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1742. }
  1743. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1744. {
  1745. if (mBfIRBuilder->mIgnoreWrites)
  1746. return mBfIRBuilder->GetFakeVal();
  1747. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1748. mBfIRBuilder->PopulateType(type);
  1749. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1750. if (!mBfIRBuilder->mIgnoreWrites)
  1751. BF_ASSERT(!prevInsertBlock.IsFake());
  1752. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1753. BfIRValue allocaInst;
  1754. if (arraySize)
  1755. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1756. else
  1757. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1758. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1759. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1760. if (name != NULL)
  1761. mBfIRBuilder->SetName(allocaInst, name);
  1762. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1763. if ((addLifetime) && (WantsLifetimes()))
  1764. {
  1765. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1766. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1767. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1768. }
  1769. return allocaInst;
  1770. }
  1771. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1772. {
  1773. if (mBfIRBuilder->mIgnoreWrites)
  1774. return mBfIRBuilder->GetFakeVal();
  1775. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1776. mBfIRBuilder->PopulateType(typeInst);
  1777. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1778. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1779. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1780. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1781. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1782. if (name != NULL)
  1783. mBfIRBuilder->SetName(allocaInst, name);
  1784. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1785. if ((addLifetime) && (WantsLifetimes()))
  1786. {
  1787. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1788. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1789. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1790. }
  1791. return allocaInst;
  1792. }
  1793. BfDeferredCallEntry* BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape, BfIRBlock valBlock)
  1794. {
  1795. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1796. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1797. /*if (mCurMethodState->mInHeadScope)
  1798. isScopeAlloc = true;*/
  1799. if (scopeData == NULL)
  1800. return NULL;
  1801. auto checkBaseType = val.mType->ToTypeInstance();
  1802. if ((checkBaseType != NULL) && (checkBaseType->IsObject()) && (!arraySize))
  1803. {
  1804. bool hadDtorCall = false;
  1805. while (checkBaseType != NULL)
  1806. {
  1807. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  1808. if (dtorMethodDef != NULL)
  1809. {
  1810. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  1811. if (dtorMethodInstance)
  1812. {
  1813. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1814. BfIRValue useVal = val.mValue;
  1815. BfIRBlock prevBlock = mBfIRBuilder->GetInsertBlock();
  1816. if (valBlock)
  1817. mBfIRBuilder->SetInsertPoint(valBlock);
  1818. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1819. if (!useVal.IsConst())
  1820. mBfIRBuilder->ClearDebugLocation(useVal);
  1821. if (valBlock)
  1822. mBfIRBuilder->SetInsertPoint(prevBlock);
  1823. if (isDynAlloc)
  1824. {
  1825. //
  1826. }
  1827. else if (condAlloca)
  1828. {
  1829. BF_ASSERT(!IsTargetingBeefBackend());
  1830. BF_ASSERT(!isDynAlloc);
  1831. auto valPtr = CreateAlloca(checkBaseType);
  1832. mBfIRBuilder->ClearDebugLocation_Last();
  1833. mBfIRBuilder->CreateAlignedStore(useVal, valPtr, checkBaseType->mAlign);
  1834. mBfIRBuilder->ClearDebugLocation_Last();
  1835. useVal = valPtr;
  1836. }
  1837. SizedArray<BfIRValue, 1> llvmArgs;
  1838. llvmArgs.push_back(useVal);
  1839. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1840. if (deferredCall != NULL)
  1841. {
  1842. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1843. if (condAlloca)
  1844. deferredCall->mArgsNeedLoad = true;
  1845. }
  1846. hadDtorCall = true;
  1847. break;
  1848. }
  1849. }
  1850. checkBaseType = checkBaseType->mBaseType;
  1851. }
  1852. return NULL;
  1853. }
  1854. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1855. if (mayEscape)
  1856. {
  1857. if ((!IsOptimized()) && (!mIsComptimeModule) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1858. {
  1859. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1860. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1861. if (!isDyn)
  1862. {
  1863. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1864. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1865. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1866. if (!dtorMethodInstance.mMethodInstance)
  1867. {
  1868. Fail(StrFormat("Unable to find %s", methodName));
  1869. }
  1870. else
  1871. {
  1872. SizedArray<BfIRValue, 1> llvmArgs;
  1873. if (IsTargetingBeefBackend())
  1874. {
  1875. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1876. //mBfIRBuilder->ClearDebugLocation_Last();
  1877. }
  1878. else
  1879. llvmArgs.push_back(val.mValue);
  1880. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1881. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1882. if (arraySize)
  1883. llvmArgs.push_back(arraySize);
  1884. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1885. }
  1886. }
  1887. else
  1888. {
  1889. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1890. {
  1891. BfIRValue clearSize = arraySize;
  1892. if (val.mType->GetStride() > 1)
  1893. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1894. const char* methodName = "SetDeletedX";
  1895. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1896. BF_ASSERT(dtorMethodInstance);
  1897. if (!dtorMethodInstance)
  1898. {
  1899. Fail(StrFormat("Unable to find %s", methodName));
  1900. }
  1901. else
  1902. {
  1903. SizedArray<BfIRValue, 1> llvmArgs;
  1904. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1905. //mBfIRBuilder->ClearDebugLocation_Last();
  1906. llvmArgs.push_back(clearSize);
  1907. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1908. }
  1909. }
  1910. else
  1911. {
  1912. intptr clearSize = val.mType->mSize;
  1913. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1914. if (constant != NULL)
  1915. clearSize = (intptr)(clearSize * constant->mInt64);
  1916. const char* funcName = "SetDeleted1";
  1917. if (clearSize >= 16)
  1918. funcName = "SetDeleted16";
  1919. else if (clearSize >= 8)
  1920. funcName = "SetDeleted8";
  1921. else if (clearSize >= 4)
  1922. funcName = "SetDeleted4";
  1923. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1924. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1925. if (!dtorMethodInstance)
  1926. {
  1927. Fail(StrFormat("Unable to find %s", funcName));
  1928. }
  1929. else
  1930. {
  1931. SizedArray<BfIRValue, 1> llvmArgs;
  1932. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1933. //mBfIRBuilder->ClearDebugLocation_Last();
  1934. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1935. }
  1936. }
  1937. }
  1938. }
  1939. }
  1940. return NULL;
  1941. }
  1942. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1943. {
  1944. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1945. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1946. return false;
  1947. auto checkTypeInstance = startTypeInstance;
  1948. while (checkTypeInstance != NULL)
  1949. {
  1950. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1951. {
  1952. if (fieldInstance.mMergedDataIdx != -1)
  1953. {
  1954. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1955. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1956. {
  1957. // For fields added in extensions, we automatically initialize those if necessary
  1958. auto fieldDef = fieldInstance.GetFieldDef();
  1959. if (!fieldDef->mDeclaringType->IsExtension())
  1960. return false;
  1961. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  1962. {
  1963. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1964. mBfIRBuilder->SaveDebugLocation();
  1965. if (localVar->IsParam())
  1966. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1967. else
  1968. {
  1969. BF_ASSERT(localVar->mDeclBlock);
  1970. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1971. }
  1972. mBfIRBuilder->ClearDebugLocation();
  1973. BfIRValue curVal;
  1974. if (localVar->mIsThis)
  1975. curVal = mBfIRBuilder->GetArgument(0);
  1976. else
  1977. curVal = localVar->mAddr;
  1978. auto subTypeInstance = startTypeInstance;
  1979. while (subTypeInstance != checkTypeInstance)
  1980. {
  1981. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1982. subTypeInstance = subTypeInstance->mBaseType;
  1983. }
  1984. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1985. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1986. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1987. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1988. mBfIRBuilder->RestoreDebugLocation();
  1989. }
  1990. localVar->mUnassignedFieldFlags &= ~checkMask;
  1991. if (localVar->mUnassignedFieldFlags == 0)
  1992. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1993. }
  1994. }
  1995. }
  1996. checkTypeInstance = checkTypeInstance->mBaseType;
  1997. }
  1998. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  1999. }
  2000. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  2001. {
  2002. BfAstNode* localNameNode = localVar->mNameNode;
  2003. if (localVar->mIsThis)
  2004. {
  2005. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  2006. }
  2007. if (localNameNode != NULL)
  2008. {
  2009. bool isOut = false;
  2010. if (localVar->mResolvedType->IsRef())
  2011. {
  2012. auto refType = (BfRefType*)localVar->mResolvedType;
  2013. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  2014. }
  2015. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  2016. {
  2017. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  2018. TryLocalVariableInit(localVar);
  2019. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  2020. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  2021. // We may have init blocks that we aren't processing here...
  2022. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  2023. deferFullAnalysis = true;
  2024. //bool deferFullAnalysis = true;
  2025. bool deferUsageWarning = deferFullAnalysis && (mCompiler->IsAutocomplete()) &&
  2026. (mCompiler->mResolvePassData->mAutoComplete->mResolveType != BfResolveType_GetFixits);
  2027. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  2028. (!localVar->mIsImplicitParam))
  2029. {
  2030. if (deferUsageWarning)
  2031. {
  2032. // Ignore
  2033. }
  2034. else if (localVar->mIsThis)
  2035. {
  2036. bool foundFields = false;
  2037. auto checkTypeInstance = mCurTypeInstance;
  2038. while (checkTypeInstance != NULL)
  2039. {
  2040. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  2041. {
  2042. if (fieldInstance.mMergedDataIdx == -1)
  2043. continue;
  2044. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  2045. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  2046. {
  2047. auto fieldDef = fieldInstance.GetFieldDef();
  2048. if (mCurMethodInstance->mMethodDef->mDeclaringType->mIsPartial)
  2049. {
  2050. if (mCurMethodInstance->mMethodDef->mDeclaringType != fieldInstance.GetFieldDef()->mDeclaringType)
  2051. {
  2052. // This extension is only responsible for its own fields
  2053. foundFields = true;
  2054. continue;
  2055. }
  2056. if (fieldDef->GetInitializer() != NULL)
  2057. {
  2058. // This initializer was handled in CtorNoBody
  2059. foundFields = true;
  2060. continue;
  2061. }
  2062. }
  2063. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  2064. {
  2065. String propName;
  2066. if (propertyDeclaration->mNameNode != NULL)
  2067. propertyDeclaration->mNameNode->ToString(propName);
  2068. if (checkTypeInstance == mCurTypeInstance)
  2069. {
  2070. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  2071. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2072. }
  2073. else
  2074. {
  2075. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  2076. TypeToString(checkTypeInstance).c_str(),
  2077. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2078. }
  2079. }
  2080. else
  2081. {
  2082. if (checkTypeInstance == mCurTypeInstance)
  2083. {
  2084. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  2085. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2086. }
  2087. else
  2088. {
  2089. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  2090. TypeToString(checkTypeInstance).c_str(),
  2091. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2092. }
  2093. }
  2094. foundFields = true;
  2095. }
  2096. }
  2097. checkTypeInstance = checkTypeInstance->mBaseType;
  2098. }
  2099. if (!foundFields)
  2100. {
  2101. if (mCurTypeInstance->mInstSize > 0)
  2102. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  2103. }
  2104. }
  2105. else if (localVar->IsParam())
  2106. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  2107. else if (!deferUsageWarning)
  2108. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2109. }
  2110. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  2111. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2112. }
  2113. }
  2114. }
  2115. void BfModule::CreateRetValLocal()
  2116. {
  2117. if (mCurMethodState->mRetVal)
  2118. {
  2119. BfLocalVariable* localDef = new BfLocalVariable();
  2120. localDef->mName = "return";
  2121. localDef->mResolvedType = mCurMethodState->mRetVal.mType;
  2122. localDef->mAddr = mCurMethodState->mRetVal.mValue;
  2123. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2124. AddLocalVariableDef(localDef);
  2125. }
  2126. else if (mCurMethodState->mRetValAddr)
  2127. {
  2128. BfLocalVariable* localDef = new BfLocalVariable();
  2129. localDef->mName = "return";
  2130. localDef->mResolvedType = CreateRefType(mCurMethodInstance->mReturnType);
  2131. localDef->mAddr = mCurMethodState->mRetValAddr;
  2132. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2133. AddLocalVariableDef(localDef);
  2134. }
  2135. }
  2136. void BfModule::MarkDynStack(BfScopeData* scopeData)
  2137. {
  2138. auto checkScope = mCurMethodState->mCurScope;
  2139. while (true)
  2140. {
  2141. if (checkScope == scopeData)
  2142. break;
  2143. checkScope->mHadOuterDynStack = true;
  2144. checkScope = checkScope->mPrevScope;
  2145. }
  2146. }
  2147. void BfModule::SaveStackState(BfScopeData* scopeData)
  2148. {
  2149. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  2150. // scopes within scopeData restore the stack
  2151. auto checkScope = mCurMethodState->mCurScope;
  2152. while (true)
  2153. {
  2154. if (checkScope == scopeData)
  2155. {
  2156. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  2157. {
  2158. if (mBfIRBuilder->mHasDebugInfo)
  2159. mBfIRBuilder->SaveDebugLocation();
  2160. auto prevPos = mBfIRBuilder->GetInsertBlock();
  2161. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  2162. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  2163. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  2164. mBfIRBuilder->SetInsertPoint(prevPos);
  2165. if (mBfIRBuilder->mHasDebugInfo)
  2166. mBfIRBuilder->RestoreDebugLocation();
  2167. }
  2168. break;
  2169. }
  2170. if (checkScope->mSavedStack)
  2171. {
  2172. for (auto usage : checkScope->mSavedStackUses)
  2173. mBfIRBuilder->EraseInstFromParent(usage);
  2174. checkScope->mSavedStackUses.Clear();
  2175. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  2176. checkScope->mSavedStack = BfIRValue();
  2177. }
  2178. checkScope = checkScope->mPrevScope;
  2179. }
  2180. }
  2181. BfIRValue BfModule::ValueScopeStart()
  2182. {
  2183. if (IsTargetingBeefBackend())
  2184. return mBfIRBuilder->CreateValueScopeStart();
  2185. return BfIRValue();
  2186. }
  2187. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  2188. {
  2189. if (valueScopeStart)
  2190. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  2191. }
  2192. BfProjectSet* BfModule::GetVisibleProjectSet()
  2193. {
  2194. if (mCurMethodState == NULL)
  2195. return NULL;
  2196. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  2197. {
  2198. HashSet<BfType*> seenTypes;
  2199. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  2200. {
  2201. if (mCurMethodState->mVisibleProjectSet.Add(project))
  2202. {
  2203. for (auto dep : project->mDependencies)
  2204. _AddProject(dep);
  2205. }
  2206. };
  2207. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  2208. {
  2209. auto typeInstance = type->ToTypeInstance();
  2210. if (typeInstance == NULL)
  2211. {
  2212. if (type->IsSizedArray())
  2213. _AddType(type->GetUnderlyingType());
  2214. return;
  2215. }
  2216. if (typeInstance->IsTuple())
  2217. {
  2218. for (auto& fieldInst : typeInstance->mFieldInstances)
  2219. {
  2220. if (fieldInst.mDataIdx != -1)
  2221. _AddType(fieldInst.mResolvedType);
  2222. }
  2223. }
  2224. _AddProject(typeInstance->mTypeDef->mProject);
  2225. if (typeInstance->mGenericTypeInfo == NULL)
  2226. return;
  2227. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2228. {
  2229. if (seenTypes.Add(type))
  2230. _AddType(type);
  2231. }
  2232. };
  2233. if (mCurTypeInstance != NULL)
  2234. _AddType(mCurTypeInstance);
  2235. auto methodState = mCurMethodState;
  2236. while (methodState != NULL)
  2237. {
  2238. if (methodState->mMethodInstance != NULL)
  2239. {
  2240. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  2241. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  2242. {
  2243. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2244. _AddType(type);
  2245. }
  2246. }
  2247. methodState = methodState->mPrevMethodState;
  2248. }
  2249. }
  2250. return &mCurMethodState->mVisibleProjectSet;
  2251. }
  2252. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2253. {
  2254. auto bfParser = astNode->GetSourceData()->ToParserData();
  2255. if (bfParser == NULL)
  2256. return NULL;
  2257. BfFileInstance** fileInstancePtr = NULL;
  2258. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2259. {
  2260. return *fileInstancePtr;
  2261. }
  2262. else
  2263. {
  2264. // It's possible two parsers have the same file name (ie: mNextRevision)
  2265. BfFileInstance** namedFileInstancePtr = NULL;
  2266. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2267. {
  2268. auto bfFileInstance = *namedFileInstancePtr;
  2269. *fileInstancePtr = bfFileInstance;
  2270. return bfFileInstance;
  2271. }
  2272. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2273. auto bfFileInstance = new BfFileInstance();
  2274. *fileInstancePtr = bfFileInstance;
  2275. *namedFileInstancePtr = bfFileInstance;
  2276. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2277. bfFileInstance->mParser = bfParser;
  2278. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2279. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasLineInfo()))
  2280. {
  2281. String fileName = bfParser->mFileName;
  2282. for (int i = 0; i < (int)fileName.length(); i++)
  2283. {
  2284. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2285. fileName[i] = DIR_SEP_CHAR;
  2286. }
  2287. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, BF_MAX(slashPos, 0)), bfParser->mMD5Hash);
  2288. }
  2289. return bfFileInstance;
  2290. }
  2291. }
  2292. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2293. {
  2294. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2295. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2296. return;
  2297. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2298. if (astNode == NULL)
  2299. return;
  2300. auto bfParser = astNode->GetSourceData()->ToParserData();
  2301. if (bfParser == NULL)
  2302. return;
  2303. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2304. {
  2305. if (mCurFilePosition.mFileInstance != NULL)
  2306. {
  2307. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2308. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2309. }
  2310. auto bfFileInstance = GetFileFromNode(astNode);
  2311. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2312. {
  2313. mCurFilePosition = bfFileInstance->mPrevPosition;
  2314. }
  2315. else
  2316. {
  2317. mCurFilePosition.mFileInstance = bfFileInstance;
  2318. mCurFilePosition.mCurLine = 0;
  2319. mCurFilePosition.mCurColumn = 0;
  2320. mCurFilePosition.mCurSrcPos = 0;
  2321. }
  2322. }
  2323. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2324. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2325. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2326. if (jumpEntry->mCharIdx > srcPos)
  2327. jumpEntry--;
  2328. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2329. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2330. mCurFilePosition.mCurColumn = 0;
  2331. while (mCurFilePosition.mCurSrcPos < srcPos)
  2332. {
  2333. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2334. {
  2335. mCurFilePosition.mCurLine++;
  2336. mCurFilePosition.mCurColumn = 0;
  2337. }
  2338. else
  2339. {
  2340. mCurFilePosition.mCurColumn++;
  2341. }
  2342. mCurFilePosition.mCurSrcPos++;
  2343. }
  2344. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2345. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasLineInfo()) && (mCurMethodState != NULL))
  2346. {
  2347. int column = mCurFilePosition.mCurColumn + 1;
  2348. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2349. {
  2350. // Set to illegal position
  2351. column = 0;
  2352. }
  2353. if (mSetIllegalSrcPosition)
  2354. column = 0;
  2355. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2356. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2357. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2358. {
  2359. // This is from a different scope...
  2360. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2361. {
  2362. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2363. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2364. }
  2365. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2366. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2367. }
  2368. else
  2369. {
  2370. if (mCurMethodState->mCurScope->mAltDIFile)
  2371. {
  2372. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2373. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2374. }
  2375. }
  2376. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2377. if (mCurMethodState->mCrossingMixin)
  2378. inlineAt = BfIRMDNode();
  2379. if ((!useDIScope) && (mIsComptimeModule))
  2380. useDIScope = wantDIFile;
  2381. if (!useDIScope)
  2382. mBfIRBuilder->ClearDebugLocation();
  2383. else
  2384. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2385. if ((flags & BfSrcPosFlag_Expression) == 0)
  2386. mBfIRBuilder->CreateStatementStart();
  2387. }
  2388. }
  2389. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2390. {
  2391. // We've turned off expr src pos (for now?)
  2392. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2393. }
  2394. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2395. {
  2396. if (mCompiler->mBfObjectTypeDef != NULL)
  2397. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2398. SetIllegalSrcPos();
  2399. }
  2400. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2401. {
  2402. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2403. {
  2404. auto curScope = mCurMethodState->mCurScope->mDIScope;
  2405. if (curScope)
  2406. {
  2407. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2408. {
  2409. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2410. mBfIRBuilder->SetCurrentDebugLocation(0, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2411. }
  2412. else
  2413. {
  2414. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2415. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2416. }
  2417. }
  2418. if ((flags & BfSrcPosFlag_Expression) == 0)
  2419. mBfIRBuilder->CreateStatementStart();
  2420. }
  2421. }
  2422. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2423. {
  2424. // We've turned off expr src pos (for now?)
  2425. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2426. }
  2427. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2428. {
  2429. if ((protection == BfProtection_Public) ||
  2430. (((protection == BfProtection_Protected) || (protection == BfProtection_ProtectedInternal)) && (allowProtected)) ||
  2431. ((protection == BfProtection_Private) && (allowPrivate)))
  2432. return true;
  2433. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2434. {
  2435. mAttributeState->mUsed = true;
  2436. return true;
  2437. }
  2438. if (((protection == BfProtection_Internal) || (protection == BfProtection_ProtectedInternal)) && (checkType != NULL))
  2439. {
  2440. if (CheckInternalProtection(checkType))
  2441. return true;
  2442. }
  2443. return false;
  2444. }
  2445. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2446. {
  2447. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2448. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2449. {
  2450. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2451. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2452. }
  2453. allowProtected = allowPrivate;
  2454. }
  2455. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2456. {
  2457. if (memberProtection == BfProtection_Hidden)
  2458. return false;
  2459. if (memberProtection == BfProtection_Public)
  2460. return true;
  2461. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2462. {
  2463. BfTypeInstance* curCheckType = mCurTypeInstance;
  2464. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2465. {
  2466. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2467. curCheckType = mixinOwner;
  2468. }
  2469. bool allowPrivate = (curCheckType != NULL) && (memberOwner->IsInstanceOf(curCheckType->mTypeDef));
  2470. if (curCheckType != NULL)
  2471. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2472. if (allowPrivate)
  2473. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2474. else
  2475. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2476. }
  2477. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2478. return true;
  2479. if ((memberProtection == BfProtection_Protected) || (memberProtection == BfProtection_ProtectedInternal))
  2480. {
  2481. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2482. {
  2483. bool allowProtected = false;
  2484. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2485. auto curCheckType = mCurTypeInstance;
  2486. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2487. {
  2488. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2489. curCheckType = mixinOwner;
  2490. }
  2491. if ((flags & BfProtectionCheckFlag_InstanceLookup) != 0)
  2492. {
  2493. auto lookupCheckType = lookupStartType;
  2494. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2495. {
  2496. if (lookupCheckType == curCheckType)
  2497. {
  2498. allowProtected = true;
  2499. break;
  2500. }
  2501. if (lookupCheckType == memberOwner)
  2502. break;
  2503. lookupCheckType = lookupCheckType->mBaseType;
  2504. if (lookupCheckType == NULL)
  2505. break;
  2506. }
  2507. }
  2508. else
  2509. {
  2510. auto lookupCheckType = curCheckType;
  2511. while (lookupCheckType->mInheritDepth >= memberOwner->mInheritDepth)
  2512. {
  2513. if (lookupCheckType == memberOwner)
  2514. {
  2515. allowProtected = true;
  2516. break;
  2517. }
  2518. lookupCheckType = lookupCheckType->mBaseType;
  2519. if (lookupCheckType == NULL)
  2520. break;
  2521. }
  2522. }
  2523. if (!allowProtected)
  2524. {
  2525. // It's possible our outer type is derived from 'memberOwner'
  2526. while (curCheckType->mTypeDef->mNestDepth > 0)
  2527. {
  2528. curCheckType = GetOuterType(curCheckType);
  2529. if (curCheckType == NULL)
  2530. break;
  2531. auto lookupCheckType = lookupStartType;
  2532. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2533. {
  2534. if (lookupCheckType == curCheckType)
  2535. {
  2536. allowProtected = true;
  2537. break;
  2538. }
  2539. if (lookupCheckType == memberOwner)
  2540. break;
  2541. lookupCheckType = lookupCheckType->mBaseType;
  2542. if (lookupCheckType == NULL)
  2543. break;
  2544. }
  2545. }
  2546. }
  2547. if (allowProtected)
  2548. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2549. else
  2550. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2551. }
  2552. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2553. return true;
  2554. }
  2555. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2556. {
  2557. mAttributeState->mUsed = true;
  2558. return true;
  2559. }
  2560. if (((memberProtection == BfProtection_Internal) || (memberProtection == BfProtection_ProtectedInternal)) && (memberOwner != NULL))
  2561. {
  2562. if (CheckInternalProtection(memberOwner->mTypeDef))
  2563. return true;
  2564. }
  2565. return false;
  2566. }
  2567. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2568. {
  2569. if (mCompiler->mResolvePassData != NULL)
  2570. {
  2571. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2572. sourceClassifier->SetElementType(astNode, elementType);
  2573. }
  2574. }
  2575. bool BfModule::PreFail()
  2576. {
  2577. if (!mIgnoreErrors)
  2578. return true;
  2579. SetFail();
  2580. return false;
  2581. }
  2582. void BfModule::SetFail()
  2583. {
  2584. if (mIgnoreErrors)
  2585. {
  2586. if (mAttributeState != NULL)
  2587. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2588. }
  2589. }
  2590. void BfModule::VerifyOnDemandMethods()
  2591. {
  2592. #ifdef _DEBUG
  2593. // if (mParentModule != NULL)
  2594. // {
  2595. // BF_ASSERT(mOnDemandMethodCount == 0);
  2596. // mParentModule->VerifyOnDemandMethods();
  2597. // return;
  2598. // }
  2599. //
  2600. // int onDemandCount = 0;
  2601. // for (auto type : mOwnedTypeInstances)
  2602. // {
  2603. // auto typeInst = type->ToTypeInstance();
  2604. // for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  2605. // {
  2606. // if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  2607. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  2608. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  2609. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  2610. // onDemandCount++;
  2611. // }
  2612. // }
  2613. //
  2614. // BF_ASSERT(mOnDemandMethodCount == onDemandCount);
  2615. #endif
  2616. }
  2617. bool BfModule::IsSkippingExtraResolveChecks()
  2618. {
  2619. if (mIsComptimeModule)
  2620. return false;
  2621. return mCompiler->IsSkippingExtraResolveChecks();
  2622. }
  2623. bool BfModule::AddErrorContext(StringImpl& errorString, BfAstNode* refNode, BfWhileSpecializingFlags& isWhileSpecializing, bool isWarning)
  2624. {
  2625. bool isWhileSpecializingMethod = false;
  2626. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2627. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2628. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2629. errorString += StrFormat("\n while generating append size calculating method");
  2630. else if (refNode == NULL)
  2631. {
  2632. if (mCurTypeInstance != NULL)
  2633. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2634. else if (mProject != NULL)
  2635. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2636. }
  2637. if (mCurTypeInstance != NULL)
  2638. {
  2639. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2640. {
  2641. // Propogate the fail all the way to the main method (assuming we're in a local method or lambda)
  2642. if (isWarning)
  2643. methodInstance->mHasWarning = true;
  2644. else
  2645. methodInstance->mHasFailed = true;
  2646. if (!methodInstance->mHasStartedDeclaration)
  2647. StartMethodDeclaration(methodInstance, NULL);
  2648. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2649. if (isSpecializedMethod)
  2650. {
  2651. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2652. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2653. if (unspecializedMethod == methodInstance)
  2654. {
  2655. // This is a local method inside a generic method
  2656. BF_ASSERT(methodInstance->mMethodDef->mIsLocalMethod);
  2657. }
  2658. else
  2659. {
  2660. if (isWarning)
  2661. {
  2662. if (unspecializedMethod->mHasWarning)
  2663. return false; // At least SOME error has already been reported
  2664. }
  2665. else
  2666. {
  2667. if (unspecializedMethod->mHasFailed)
  2668. return false; // At least SOME error has already been reported
  2669. }
  2670. }
  2671. }
  2672. if (isSpecializedMethod)
  2673. {
  2674. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2675. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2676. isWhileSpecializingMethod = true;
  2677. }
  2678. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2679. {
  2680. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2681. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2682. isWhileSpecializingMethod = true;
  2683. }
  2684. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2685. {
  2686. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2687. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2688. }
  2689. return true;
  2690. };
  2691. bool hadMethodInstance = false;
  2692. if (mCurMethodState != NULL)
  2693. {
  2694. auto checkMethodState = mCurMethodState;
  2695. while (checkMethodState != NULL)
  2696. {
  2697. auto methodInstance = checkMethodState->mMethodInstance;
  2698. if (methodInstance == NULL)
  2699. {
  2700. checkMethodState = checkMethodState->mPrevMethodState;
  2701. continue;
  2702. }
  2703. hadMethodInstance = true;
  2704. if (!_CheckMethodInstance(methodInstance))
  2705. return false;
  2706. checkMethodState = checkMethodState->mPrevMethodState;
  2707. }
  2708. }
  2709. if ((!hadMethodInstance) && (mCurMethodInstance != NULL))
  2710. {
  2711. if (!_CheckMethodInstance(mCurMethodInstance))
  2712. return false;
  2713. }
  2714. }
  2715. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2716. {
  2717. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2718. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2719. }
  2720. return true;
  2721. }
  2722. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent, bool deferError)
  2723. {
  2724. BP_ZONE("BfModule::Fail");
  2725. if (mIgnoreErrors)
  2726. {
  2727. mHadIgnoredError = true;
  2728. if (mAttributeState != NULL)
  2729. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2730. return NULL;
  2731. }
  2732. if (!mReportErrors)
  2733. {
  2734. mCompiler->mPassInstance->SilentFail();
  2735. return NULL;
  2736. }
  2737. if (refNode != NULL)
  2738. refNode = BfNodeToNonTemporary(refNode);
  2739. //BF_ASSERT(refNode != NULL);
  2740. if (mIsComptimeModule)
  2741. {
  2742. if (auto ceDbgState = GetCeDbgState())
  2743. {
  2744. // Follow normal fail path
  2745. }
  2746. else
  2747. {
  2748. mHadBuildError = true;
  2749. if ((mCompiler->mCeMachine->mCurContext != NULL) && (mCompiler->mCeMachine->mCurContext->mCurCallSource != NULL) &&
  2750. (mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode != NULL))
  2751. {
  2752. BfError* bfError = mCompiler->mPassInstance->Fail("Comptime method generation had errors",
  2753. mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode);
  2754. if (bfError != NULL)
  2755. mCompiler->mPassInstance->MoreInfo(error, refNode);
  2756. return bfError;
  2757. }
  2758. return NULL;
  2759. }
  2760. }
  2761. if ((mCurMethodState != NULL) && (mCurMethodState->mConstResolveState != NULL) && (mCurMethodState->mConstResolveState->mInCalcAppend))
  2762. {
  2763. mCurMethodState->mConstResolveState->mFailed = true;
  2764. return NULL;
  2765. }
  2766. if (mCurMethodInstance != NULL)
  2767. mCurMethodInstance->mHasFailed = true;
  2768. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2769. return NULL;
  2770. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2771. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2772. if (!mHadBuildError)
  2773. mHadBuildError = true;
  2774. if (mParentModule != NULL)
  2775. mParentModule->mHadBuildError = true;
  2776. if (mCurTypeInstance != NULL)
  2777. AddFailType(mCurTypeInstance);
  2778. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2779. String errorString = error;
  2780. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2781. if (!AddErrorContext(errorString, refNode, isWhileSpecializing, false))
  2782. return NULL;
  2783. BfError* bfError = NULL;
  2784. if (isWhileSpecializing)
  2785. deferError = true;
  2786. if (!mHadBuildError)
  2787. mHadBuildError = true;
  2788. // Check mixins
  2789. {
  2790. auto checkMethodState = mCurMethodState;
  2791. while (checkMethodState != NULL)
  2792. {
  2793. auto rootMixinState = checkMethodState->GetRootMixinState();
  2794. if (rootMixinState != NULL)
  2795. {
  2796. String mixinErr = StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str());
  2797. if (deferError)
  2798. bfError = mCompiler->mPassInstance->DeferFail(mixinErr, rootMixinState->mSource);
  2799. else
  2800. bfError = mCompiler->mPassInstance->Fail(mixinErr, rootMixinState->mSource);
  2801. if (bfError == NULL)
  2802. return NULL;
  2803. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2804. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2805. auto mixinState = checkMethodState->mMixinState;
  2806. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2807. {
  2808. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2809. mixinState = mixinState->mPrevMixinState;
  2810. }
  2811. return bfError;
  2812. }
  2813. checkMethodState = checkMethodState->mPrevMethodState;
  2814. }
  2815. }
  2816. if (deferError)
  2817. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2818. else if (refNode == NULL)
  2819. bfError = mCompiler->mPassInstance->Fail(errorString);
  2820. else
  2821. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2822. if (bfError != NULL)
  2823. {
  2824. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2825. bfError->mProject = mProject;
  2826. bfError->mIsPersistent = isPersistent;
  2827. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2828. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2829. else if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2830. mCompiler->mPassInstance->MoreInfo("Error in emitted code", mCurMethodState->mEmitRefNode);
  2831. }
  2832. return bfError;
  2833. }
  2834. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2835. {
  2836. if (mHadBuildError)
  2837. return NULL;
  2838. return Fail(error, refNode);
  2839. }
  2840. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2841. {
  2842. if (mIgnoreErrors)
  2843. return NULL;
  2844. if (refNode != NULL)
  2845. refNode = BfNodeToNonTemporary(refNode);
  2846. mHadBuildError = true;
  2847. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2848. if (bfError != NULL)
  2849. bfError->mProject = mProject;
  2850. return bfError;
  2851. }
  2852. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent, bool showInSpecialized)
  2853. {
  2854. if (mIgnoreErrors || mIgnoreWarnings)
  2855. return NULL;
  2856. if (!mReportErrors)
  2857. {
  2858. mCompiler->mPassInstance->SilentFail();
  2859. return NULL;
  2860. }
  2861. BfAstNode* unwarnNode = refNode;
  2862. //
  2863. {
  2864. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2865. while (parentNodeEntry != NULL)
  2866. {
  2867. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2868. break;
  2869. unwarnNode = parentNodeEntry->mNode;
  2870. parentNodeEntry = parentNodeEntry->mPrev;
  2871. }
  2872. }
  2873. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2874. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2875. {
  2876. return NULL;
  2877. }
  2878. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2879. if (mCurMethodInstance != NULL)
  2880. {
  2881. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2882. {
  2883. if (!showInSpecialized)
  2884. return NULL;
  2885. }
  2886. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2887. return NULL; // No ctorCalcAppend warnings
  2888. }
  2889. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2890. {
  2891. if (!showInSpecialized)
  2892. return NULL;
  2893. }
  2894. if (refNode != NULL)
  2895. refNode = BfNodeToNonTemporary(refNode);
  2896. String warningString = warning;
  2897. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2898. if (!AddErrorContext(warningString, refNode, isWhileSpecializing, true))
  2899. return NULL;
  2900. bool deferWarning = isWhileSpecializing != BfWhileSpecializingFlag_None;
  2901. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2902. {
  2903. // We used to bubble up warnings into the mixin injection site, BUT
  2904. // we are now assuming any relevant warnings will be given at the declaration site
  2905. return NULL;
  2906. }
  2907. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2908. {
  2909. BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Emitted code had errors", mCurMethodState->mEmitRefNode);
  2910. if (bfError != NULL)
  2911. mCompiler->mPassInstance->MoreInfo(warningString, refNode);
  2912. return bfError;
  2913. }
  2914. BfError* bfError;
  2915. if (refNode != NULL)
  2916. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warningString, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2917. else
  2918. bfError = mCompiler->mPassInstance->Warn(warningNum, warningString);
  2919. if (bfError != NULL)
  2920. {
  2921. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2922. bfError->mProject = mProject;
  2923. AddFailType(mCurTypeInstance);
  2924. mHadBuildWarning = true;
  2925. bfError->mIsPersistent = isPersistent;
  2926. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2927. {
  2928. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2929. if (parser != NULL)
  2930. {
  2931. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2932. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2933. if (warningNum != 0)
  2934. {
  2935. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  2936. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  2937. }
  2938. }
  2939. }
  2940. }
  2941. return bfError;
  2942. }
  2943. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfFieldInstance* fieldInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  2944. {
  2945. if (customAttributes == NULL)
  2946. return;
  2947. auto _AddDeclarationMoreInfo = [&]()
  2948. {
  2949. if (methodInstance != NULL)
  2950. {
  2951. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  2952. mCompiler->mPassInstance->MoreInfo(
  2953. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  2954. methodInstance->mMethodDef->GetRefNode());
  2955. }
  2956. else
  2957. {
  2958. mCompiler->mPassInstance->MoreInfo(
  2959. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  2960. typeInstance->mTypeDef->GetRefNode());
  2961. }
  2962. };
  2963. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  2964. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  2965. if ((customAttribute != NULL) && (targetSrc != NULL))
  2966. {
  2967. String err;
  2968. if (fieldInstance != NULL)
  2969. err = StrFormat("'%s' is obsolete", FieldToString(fieldInstance).c_str());
  2970. else if (methodInstance != NULL)
  2971. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  2972. else
  2973. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2974. bool isError = false;
  2975. if (customAttribute->mCtorArgs.size() >= 1)
  2976. {
  2977. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  2978. if (constant->mTypeCode == BfTypeCode_Boolean)
  2979. {
  2980. isError = constant->mBool;
  2981. }
  2982. else if (constant->mTypeCode == BfTypeCode_StringId)
  2983. {
  2984. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2985. if (str != NULL)
  2986. {
  2987. err += ":\n '";
  2988. err += *str;
  2989. err += "'";
  2990. }
  2991. if (customAttribute->mCtorArgs.size() >= 2)
  2992. {
  2993. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  2994. isError = constant->mBool;
  2995. }
  2996. }
  2997. }
  2998. BfError* error = NULL;
  2999. if (isError)
  3000. error = Fail(err, targetSrc);
  3001. else
  3002. error = Warn(0, err, targetSrc, false, true);
  3003. if (error != NULL)
  3004. _AddDeclarationMoreInfo();
  3005. }
  3006. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  3007. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3008. {
  3009. String err;
  3010. if (fieldInstance != NULL)
  3011. err += StrFormat("Method error: '", FieldToString(fieldInstance).c_str());
  3012. else if (methodInstance != NULL)
  3013. err += StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  3014. else
  3015. err += StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3016. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3017. if (str != NULL)
  3018. err += *str;
  3019. err += "'";
  3020. if (Fail(err, targetSrc) != NULL)
  3021. _AddDeclarationMoreInfo();
  3022. }
  3023. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  3024. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  3025. {
  3026. String err;
  3027. if (fieldInstance != NULL)
  3028. err += StrFormat("Field warning: '", FieldToString(fieldInstance).c_str());
  3029. else if (methodInstance != NULL)
  3030. err += StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  3031. else
  3032. err += StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3033. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3034. if (str != NULL)
  3035. err += *str;
  3036. err += "'";
  3037. if (Warn(0, err, targetSrc, false, true) != NULL)
  3038. _AddDeclarationMoreInfo();
  3039. }
  3040. }
  3041. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  3042. {
  3043. if (mBfIRBuilder->mOpFailed)
  3044. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  3045. }
  3046. void BfModule::FatalError(const StringImpl& error, const char* file, int line)
  3047. {
  3048. static bool sHadFatalError = false;
  3049. static bool sHadReentrancy = false;
  3050. if (sHadFatalError)
  3051. {
  3052. return;
  3053. sHadReentrancy = true;
  3054. }
  3055. sHadFatalError = true;
  3056. String fullError = error;
  3057. if (file != NULL)
  3058. fullError += StrFormat(" at %s:%d", file, line);
  3059. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3060. if (mCurTypeInstance != NULL)
  3061. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3062. if (mCurMethodInstance != NULL)
  3063. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3064. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3065. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3066. if (sHadReentrancy)
  3067. fullError += "\nError had reentrancy";
  3068. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  3069. }
  3070. void BfModule::NotImpl(BfAstNode* astNode)
  3071. {
  3072. Fail("INTERNAL ERROR: Not implemented", astNode);
  3073. }
  3074. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  3075. {
  3076. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  3077. if (!allowPrivate)
  3078. allowPrivate |= memberType->IsInterface();
  3079. bool allowProtected = allowPrivate;
  3080. //TODO: We had this commented out, but this makes accessing protected properties fail
  3081. if (mCurTypeInstance != NULL)
  3082. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  3083. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  3084. {
  3085. return false;
  3086. }
  3087. return true;
  3088. }
  3089. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  3090. {
  3091. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  3092. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  3093. auto memberTypeInstance = memberType->ToTypeInstance();
  3094. if (memberTypeInstance == NULL)
  3095. {
  3096. auto underlyingType = memberType->GetUnderlyingType();
  3097. if (underlyingType != NULL)
  3098. return CheckDefineMemberProtection(protection, underlyingType);
  3099. return true;
  3100. }
  3101. if (memberTypeInstance->mTypeDef->mProtection < protection)
  3102. return false;
  3103. if (memberTypeInstance->IsGenericTypeInstance())
  3104. {
  3105. // When we're a generic struct, our data layout can depend on our generic parameters as well
  3106. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  3107. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3108. {
  3109. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  3110. return false;
  3111. }
  3112. }
  3113. return true;
  3114. }
  3115. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags, BfDepContext* depContext)
  3116. {
  3117. if (usedType == userType)
  3118. return;
  3119. if (((flags & BfDependencyMap::DependencyFlag_ConstValue) != 0) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_FieldType))
  3120. {
  3121. // This can be an `int32[UsedType.cVal]` type reference
  3122. flags = (BfDependencyMap::DependencyFlags)(flags | BfDependencyMap::DependencyFlag_ValueTypeSizeDep);
  3123. }
  3124. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  3125. {
  3126. if (userType->IsMethodRef())
  3127. {
  3128. // We cannot short-circuit dependencies because of method group ref counting
  3129. }
  3130. else
  3131. return;
  3132. }
  3133. if (usedType->IsSpecializedByAutoCompleteMethod())
  3134. {
  3135. if ((flags & (BfDependencyMap::DependencyFlag_TypeGenericArg | BfDependencyMap::DependencyFlag_MethodGenericArg |
  3136. BfDependencyMap::DependencyFlag_OuterType | BfDependencyMap::DependencyFlag_DerivedFrom)) == 0)
  3137. return;
  3138. }
  3139. // if (usedType->IsBoxed())
  3140. // {
  3141. // NOP;
  3142. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  3143. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  3144. // {
  3145. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  3146. // }
  3147. // }
  3148. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  3149. // BfType* origUsedType = usedType;
  3150. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  3151. // if (isDataAccess)
  3152. // {
  3153. // while (true)
  3154. // {
  3155. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  3156. // usedType = usedType->GetUnderlyingType();
  3157. // else if (usedType->IsArray())
  3158. // {
  3159. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  3160. // }
  3161. // else
  3162. // break;
  3163. // }
  3164. // }
  3165. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  3166. {
  3167. bool addType = true;
  3168. auto checkType = usedType;
  3169. PopulateType(checkType, BfPopulateType_Data);
  3170. if (checkType->IsValuelessType())
  3171. addType = false;
  3172. else if (checkType->IsPrimitiveType())
  3173. addType = false;
  3174. else
  3175. {
  3176. auto checkTypeInst = checkType->ToTypeInstance();
  3177. if (checkTypeInst == NULL)
  3178. {
  3179. addType = false;
  3180. }
  3181. else
  3182. {
  3183. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  3184. addType = false;
  3185. }
  3186. }
  3187. if (addType)
  3188. {
  3189. auto checkTypeInst = checkType->ToTypeInstance();
  3190. if (checkTypeInst->mHotTypeData != NULL)
  3191. {
  3192. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  3193. BF_ASSERT(hotTypeVersion != NULL);
  3194. if (hotTypeVersion != NULL)
  3195. {
  3196. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  3197. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  3198. (checkType->IsComposite()))
  3199. isAllocation = true;
  3200. if (isAllocation)
  3201. {
  3202. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  3203. }
  3204. else
  3205. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  3206. }
  3207. }
  3208. }
  3209. }
  3210. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  3211. {
  3212. auto usingModule = userType->GetModule();
  3213. BfModule* usedModule;
  3214. if (usedType->IsFunction())
  3215. {
  3216. if (mCompiler->mFunctionTypeDef != NULL)
  3217. {
  3218. auto functionType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  3219. usedModule = functionType->GetModule();
  3220. }
  3221. }
  3222. else
  3223. usedModule = usedType->GetModule();
  3224. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  3225. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  3226. {
  3227. if ((flags & ~(BfDependencyMap::DependencyFlag_OuterType)) == 0)
  3228. {
  3229. // Not a 'use' dependency
  3230. }
  3231. else
  3232. {
  3233. usingModule->mModuleRefs.Add(usedModule);
  3234. }
  3235. }
  3236. }
  3237. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  3238. {
  3239. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  3240. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  3241. if (genericArg == usedType)
  3242. return;
  3243. }
  3244. auto depFlag = flags;
  3245. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  3246. {
  3247. if (usedType->IsDependendType())
  3248. {
  3249. // Cause a rebuild but not an outright deletion of the type
  3250. // We can only do this if the 'usedType' can actually hold the dependency which can actually trigger a deletion chain
  3251. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef;
  3252. }
  3253. }
  3254. if (usedType->IsTypeAlias())
  3255. {
  3256. auto underlyingType = usedType->GetUnderlyingType();
  3257. if (underlyingType != NULL)
  3258. {
  3259. BfDepContext newDepContext;
  3260. if (depContext == NULL)
  3261. depContext = &newDepContext;
  3262. if (++depContext->mAliasDepth > 8)
  3263. {
  3264. if (!depContext->mDeepSeenAliases.Add(underlyingType))
  3265. return; // Circular!
  3266. }
  3267. AddDependency(underlyingType, userType, depFlag);
  3268. }
  3269. }
  3270. else if (!usedType->IsGenericTypeInstance())
  3271. {
  3272. auto underlyingType = usedType->GetUnderlyingType();
  3273. if (underlyingType != NULL)
  3274. AddDependency(underlyingType, userType, depFlag);
  3275. }
  3276. BfDependedType* checkDType = usedType->ToDependedType();
  3277. if (checkDType == NULL)
  3278. return;
  3279. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  3280. mContext->MarkAsReferenced(checkDType);
  3281. #ifdef _DEBUG
  3282. // If a MethodRef depends ON US, that means it's a local method that we own
  3283. if (userType->IsMethodRef())
  3284. {
  3285. auto methodRefType = (BfMethodRefType*)userType;
  3286. BF_ASSERT(methodRefType->mOwner == checkDType);
  3287. }
  3288. #endif
  3289. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  3290. return;
  3291. if ((checkDType->IsGenericTypeInstance()) && (!userType->IsMethodRef()))
  3292. {
  3293. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  3294. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3295. {
  3296. AddDependency(genericArg, userType, depFlag);
  3297. }
  3298. }
  3299. if (checkDType->IsTuple())
  3300. {
  3301. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  3302. {
  3303. if (field.mDataIdx != -1)
  3304. AddDependency(field.mResolvedType, userType, depFlag);
  3305. }
  3306. }
  3307. }
  3308. void BfModule::AddDependency(BfGenericParamInstance* genericParam, BfTypeInstance* usingType)
  3309. {
  3310. if ((genericParam->mExternType != NULL) && (!genericParam->mExternType->IsGenericParam()))
  3311. AddDependency(genericParam->mExternType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3312. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  3313. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3314. for (auto& operatorConstraint : genericParam->mOperatorConstraints)
  3315. {
  3316. if (operatorConstraint.mLeftType != NULL)
  3317. AddDependency(operatorConstraint.mLeftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3318. if (operatorConstraint.mRightType != NULL)
  3319. AddDependency(operatorConstraint.mRightType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3320. }
  3321. if (genericParam->mTypeConstraint != NULL)
  3322. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3323. }
  3324. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  3325. {
  3326. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  3327. {
  3328. if (methodInstance->mHotMethod == NULL)
  3329. CheckHotMethod(methodInstance, "");
  3330. BF_ASSERT(methodInstance->mHotMethod != NULL);
  3331. if (devirtualized)
  3332. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  3333. else
  3334. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  3335. }
  3336. }
  3337. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  3338. {
  3339. auto checkTypeInst = typeInst;
  3340. while (checkTypeInst != NULL)
  3341. {
  3342. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  3343. return true;
  3344. checkTypeInst = checkTypeInst->mBaseType;
  3345. }
  3346. return false;
  3347. }
  3348. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  3349. {
  3350. if (mContext->mCurTypeState == NULL)
  3351. return;
  3352. BP_ZONE("PopulateGlobalContainersList");
  3353. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  3354. if ((userTypeDef == NULL) && (mCurMethodInstance != NULL))
  3355. userTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  3356. if (userTypeDef == NULL)
  3357. userTypeDef = mCurTypeInstance->mTypeDef;
  3358. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  3359. {
  3360. mContext->mCurTypeState->mGlobalContainers.Clear();
  3361. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  3362. {
  3363. BfAtomComposite findStr;
  3364. if (namespaceIdx != -1)
  3365. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  3366. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  3367. while (typeDefItr)
  3368. {
  3369. auto typeDef = *typeDefItr;
  3370. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  3371. {
  3372. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  3373. {
  3374. BfGlobalContainerEntry globalEntry;
  3375. globalEntry.mTypeDef = typeDef;
  3376. globalEntry.mTypeInst = NULL;
  3377. typeDef->PopulateMemberSets();
  3378. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  3379. }
  3380. }
  3381. else if (!typeDef->mIsPartial)
  3382. {
  3383. //break;
  3384. }
  3385. typeDefItr.MoveToNextHashMatch();
  3386. }
  3387. }
  3388. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  3389. }
  3390. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  3391. // reifing types
  3392. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  3393. {
  3394. if (globalEntry.mTypeInst == NULL)
  3395. {
  3396. bool include = false;
  3397. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  3398. include = true;
  3399. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  3400. {
  3401. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  3402. include = true;
  3403. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  3404. include = true;
  3405. }
  3406. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  3407. {
  3408. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  3409. include = true;
  3410. }
  3411. if (include)
  3412. {
  3413. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  3414. if (type != NULL)
  3415. globalEntry.mTypeInst = type->ToTypeInstance();
  3416. }
  3417. }
  3418. }
  3419. }
  3420. BfStaticSearch* BfModule::GetStaticSearch()
  3421. {
  3422. auto activeTypeDef = GetActiveTypeDef();
  3423. BfStaticSearch* staticSearch = NULL;
  3424. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3425. return staticSearch;
  3426. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3427. return staticSearch;
  3428. return NULL;
  3429. }
  3430. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  3431. {
  3432. auto activeTypeDef = GetActiveTypeDef();
  3433. BfInternalAccessSet* internalAccessSet = NULL;
  3434. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3435. return internalAccessSet;
  3436. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3437. return internalAccessSet;
  3438. return NULL;
  3439. }
  3440. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  3441. {
  3442. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  3443. return true;
  3444. if ((mCurMethodInstance != NULL) &&
  3445. ((mCurMethodInstance->mIsUnspecializedVariation) || (mCurMethodInstance->IsSpecializedGenericMethod())))
  3446. return true;
  3447. auto internalAccessSet = GetInternalAccessSet();
  3448. if (internalAccessSet == NULL)
  3449. return false;
  3450. for (auto& nameComposite : internalAccessSet->mNamespaces)
  3451. {
  3452. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  3453. return true;
  3454. }
  3455. for (auto internalType : internalAccessSet->mTypes)
  3456. {
  3457. auto checkTypeDef = usingTypeDef->GetDefinition();
  3458. while (checkTypeDef != NULL)
  3459. {
  3460. if (checkTypeDef == internalType->mTypeDef->GetDefinition())
  3461. return true;
  3462. checkTypeDef = checkTypeDef->mOuterType;
  3463. }
  3464. }
  3465. return false;
  3466. }
  3467. void PrintUsers(llvm::MDNode* md);
  3468. BfModuleOptions BfModule::GetModuleOptions()
  3469. {
  3470. if (mIsScratchModule)
  3471. return BfModuleOptions();
  3472. if (mModuleOptions != NULL)
  3473. return *mModuleOptions;
  3474. BfModuleOptions moduleOptions;
  3475. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3476. if (mProject != NULL)
  3477. {
  3478. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3479. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3480. }
  3481. auto headModule = this;
  3482. while (headModule->mParentModule != NULL)
  3483. headModule = headModule->mParentModule;
  3484. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata") || mIsSpecialModule);
  3485. if (headModule->mOwnedTypeInstances.size() > 0)
  3486. {
  3487. auto typeInst = headModule->mOwnedTypeInstances[0];
  3488. if (typeInst->mTypeOptionsIdx == -2)
  3489. PopulateType(typeInst);
  3490. if (typeInst->mTypeOptionsIdx != -1)
  3491. {
  3492. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3493. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3494. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3495. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3496. }
  3497. }
  3498. return moduleOptions;
  3499. }
  3500. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3501. {
  3502. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3503. return BfCheckedKind_Unchecked;
  3504. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3505. auto typeOptions = GetTypeOptions();
  3506. if (typeOptions != NULL)
  3507. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3508. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3509. }
  3510. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3511. {
  3512. BF_ASSERT(typeInstance != NULL);
  3513. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_InFailTypes) != 0)
  3514. return;
  3515. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_InFailTypes);
  3516. mContext->mFailTypes.TryAdd(typeInstance, BfFailKind_Normal);
  3517. }
  3518. void BfModule::DeferRebuildType(BfTypeInstance* typeInstance)
  3519. {
  3520. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_RebuildQueued) != 0)
  3521. return;
  3522. mCompiler->mHasQueuedTypeRebuilds = true;
  3523. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_RebuildQueued);
  3524. AddFailType(typeInstance);
  3525. }
  3526. void BfModule::CheckAddFailType()
  3527. {
  3528. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3529. // but we still need to add the owning type to the FailTypes list
  3530. //.. OLD:
  3531. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3532. /*if (mCurTypeInstance->mModule != this)
  3533. return;*/
  3534. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3535. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3536. // being recompiled. This forces types with warnings to be recompiled.
  3537. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3538. // constantly warning-aware
  3539. if ((mHadBuildError) ||
  3540. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3541. {
  3542. //mContext->mFailTypes.Add(mCurTypeInstance);
  3543. }
  3544. }
  3545. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3546. {
  3547. if (!mCompiler->IsHotCompile())
  3548. return;
  3549. typeInst->mDirty = true;
  3550. for (auto& dep : typeInst->mDependencyMap)
  3551. {
  3552. auto depType = dep.mKey;
  3553. auto depFlags = dep.mValue.mFlags;
  3554. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3555. {
  3556. MarkDerivedDirty(depType->ToTypeInstance());
  3557. }
  3558. }
  3559. }
  3560. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3561. {
  3562. auto fieldType = fieldInstance->GetResolvedType();
  3563. auto field = fieldInstance->GetFieldDef();
  3564. if (fieldType->IsVar())
  3565. return;
  3566. BfIRValue initValue;
  3567. if (field->mIsConst)
  3568. {
  3569. if (fieldType->IsPointer())
  3570. fieldType = fieldType->GetUnderlyingType();
  3571. }
  3572. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3573. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3574. storageKind = BfIRStorageKind_Export;
  3575. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3576. storageKind = BfIRStorageKind_Import;
  3577. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3578. initValue = GetDefaultValue(fieldType);
  3579. if (fieldInstance->mOwner->IsUnspecializedType())
  3580. {
  3581. // Placeholder
  3582. auto ptrVal = CreatePointerType(fieldType);
  3583. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3584. }
  3585. else
  3586. {
  3587. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3588. StringT<4096> staticVarName;
  3589. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3590. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3591. {
  3592. BfIRType irType;
  3593. if (fieldInstance->IsAppendedObject())
  3594. {
  3595. irType = mBfIRBuilder->MapTypeInst(fieldType->ToTypeInstance(), BfIRPopulateType_Eventually_Full);
  3596. initValue = mBfIRBuilder->CreateConstAggZero(irType);
  3597. }
  3598. else
  3599. irType = mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full);
  3600. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3601. irType,
  3602. false,
  3603. BfIRLinkageType_External,
  3604. initValue,
  3605. staticVarName,
  3606. isThreadLocal);
  3607. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3608. if (storageKind != BfIRStorageKind_Normal)
  3609. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3610. BF_ASSERT(globalVar);
  3611. mStaticFieldRefs[fieldInstance] = globalVar;
  3612. }
  3613. }
  3614. }
  3615. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3616. {
  3617. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3618. BfType* fieldType = NULL;
  3619. if (fieldInstance != NULL)
  3620. {
  3621. fieldType = fieldInstance->GetResolvedType();
  3622. if (fieldType == NULL)
  3623. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3624. }
  3625. else
  3626. {
  3627. BF_ASSERT(mCompiler->IsAutocomplete());
  3628. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3629. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3630. {
  3631. fieldType = typeInstance;
  3632. }
  3633. else
  3634. {
  3635. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3636. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3637. if (isLet || isVar)
  3638. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3639. else
  3640. fieldType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  3641. if (fieldType == NULL)
  3642. fieldType = mContext->mBfObjectType;
  3643. }
  3644. }
  3645. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3646. return;
  3647. if (mContext->mFieldResolveReentrys.size() > 1)
  3648. {
  3649. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3650. {
  3651. String failStr = "Circular data reference detected between the following fields:";
  3652. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3653. {
  3654. if (i > 1)
  3655. failStr += ",";
  3656. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3657. }
  3658. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3659. if (err)
  3660. err->mIsPersistent = true;
  3661. return;
  3662. }
  3663. }
  3664. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3665. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3666. if (fieldInstance == NULL)
  3667. popTypeResolveReentry.Pop();
  3668. auto typeDef = typeInstance->mTypeDef;
  3669. BfIRValue constValue;
  3670. if (fieldDef->mIsExtern)
  3671. {
  3672. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3673. {
  3674. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3675. Fail("Extern consts must be pointer types", fieldDef->mTypeRef);
  3676. }
  3677. if (fieldDef->GetInitializer() != NULL)
  3678. {
  3679. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3680. Fail("Extern consts cannot have initializers", fieldDef->GetNameNode());
  3681. }
  3682. }
  3683. else if (fieldDef->GetInitializer() == NULL)
  3684. {
  3685. if (fieldDef->IsEnumCaseEntry())
  3686. {
  3687. if (typeInstance->IsTypedPrimitive())
  3688. {
  3689. BfFieldInstance* prevFieldInstance = NULL;
  3690. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3691. {
  3692. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3693. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3694. {
  3695. prevFieldInstance = checkFieldInst;
  3696. break;
  3697. }
  3698. }
  3699. if (prevFieldInstance == NULL)
  3700. constValue = GetConstValue(0, typeInstance);
  3701. else
  3702. {
  3703. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3704. if (prevFieldInstance->mConstIdx == -1)
  3705. {
  3706. if (!mCompiler->IsAutocomplete())
  3707. AssertErrorState();
  3708. constValue = GetConstValue(0, typeInstance);
  3709. }
  3710. else
  3711. {
  3712. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3713. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3714. }
  3715. }
  3716. }
  3717. }
  3718. else
  3719. {
  3720. Fail("Const requires initializer", fieldDef->GetNameNode());
  3721. }
  3722. }
  3723. else if (mBfIRBuilder != NULL)
  3724. {
  3725. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3726. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3727. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3728. BfMethodState methodState;
  3729. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3730. methodState.mTempKind = BfMethodState::TempKind_Static;
  3731. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3732. if ((fieldType->IsVar()) || (fieldType->IsUndefSizedArray()))
  3733. {
  3734. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3735. if (!initValue)
  3736. {
  3737. AssertErrorState();
  3738. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3739. }
  3740. if (fieldInstance != NULL)
  3741. {
  3742. if (fieldType->IsUndefSizedArray())
  3743. {
  3744. if ((initValue.mType->IsSizedArray()) && (initValue.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3745. {
  3746. fieldInstance->mResolvedType = initValue.mType;
  3747. }
  3748. }
  3749. else
  3750. fieldInstance->mResolvedType = initValue.mType;
  3751. }
  3752. constValue = initValue.mValue;
  3753. }
  3754. else
  3755. {
  3756. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3757. constValue = uncastedInitValue.mValue;
  3758. }
  3759. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3760. {
  3761. // Illegal
  3762. constValue = BfIRValue();
  3763. }
  3764. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3765. }
  3766. if (fieldInstance != NULL)
  3767. {
  3768. fieldType = fieldInstance->GetResolvedType();
  3769. if ((fieldType == NULL) || (fieldType->IsVar()))
  3770. {
  3771. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3772. AssertErrorState();
  3773. // Default const type is 'int'
  3774. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3775. if (fieldInstance != NULL)
  3776. {
  3777. fieldInstance->mResolvedType = initValue.mType;
  3778. }
  3779. constValue = initValue.mValue;
  3780. }
  3781. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3782. {
  3783. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3784. CurrentAddToConstHolder(constValue);
  3785. fieldInstance->mConstIdx = constValue.mId;
  3786. }
  3787. }
  3788. }
  3789. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3790. {
  3791. bool isDeclType = (field->mFieldDeclaration != NULL) && BfNodeDynCastExact<BfExprModTypeRef>(field->mTypeRef) != NULL;
  3792. auto fieldType = fieldInstance->GetResolvedType();
  3793. if ((field->mIsConst) && (!isDeclType))
  3794. {
  3795. ResolveConstField(typeInstance, fieldInstance, field);
  3796. return fieldInstance->GetResolvedType();
  3797. }
  3798. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3799. if (!fieldInstance->mIsInferredType)
  3800. return fieldType;
  3801. if ((!fieldType->IsVar()) && (!fieldType->IsUndefSizedArray()))
  3802. return fieldType;
  3803. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3804. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3805. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mType != typeInstance);
  3806. auto typeDef = typeInstance->mTypeDef;
  3807. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3808. {
  3809. AssertErrorState();
  3810. return fieldType;
  3811. }
  3812. bool hadInferenceCycle = false;
  3813. if (mContext->mFieldResolveReentrys.size() > 1)
  3814. {
  3815. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3816. {
  3817. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3818. {
  3819. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3820. auto fieldDef = fieldInst->GetFieldDef();
  3821. auto fieldOwner = fieldInst->mOwner;
  3822. auto fieldModule = fieldOwner->mModule;
  3823. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3824. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3825. }
  3826. return fieldType;
  3827. }
  3828. }
  3829. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3830. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3831. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3832. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3833. if ((field->GetInitializer() == NULL) && (!isDeclType))
  3834. {
  3835. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3836. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3837. return fieldType;
  3838. }
  3839. BfType* resolvedType = NULL;
  3840. if (!hadInferenceCycle)
  3841. {
  3842. BfTypeState typeState;
  3843. typeState.mPrevState = mContext->mCurTypeState;
  3844. typeState.mType = typeInstance;
  3845. typeState.mCurFieldDef = field;
  3846. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3847. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3848. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3849. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3850. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3851. BfMethodState methodState;
  3852. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3853. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3854. if (!staticOnly)
  3855. {
  3856. //BfLocalVariable localVar;
  3857. //methodState.mLocals.push_back(localVar);
  3858. }
  3859. if (isDeclType)
  3860. {
  3861. auto fieldDef = fieldInstance->GetFieldDef();
  3862. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3863. }
  3864. else
  3865. {
  3866. BfTypedValue valueFromExpr;
  3867. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3868. FixIntUnknown(valueFromExpr);
  3869. if (fieldType->IsUndefSizedArray())
  3870. {
  3871. if ((valueFromExpr.mType != NULL) && (valueFromExpr.mType->IsSizedArray()) && (valueFromExpr.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3872. resolvedType = valueFromExpr.mType;
  3873. }
  3874. else
  3875. resolvedType = valueFromExpr.mType;
  3876. }
  3877. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3878. }
  3879. if (resolvedType == NULL)
  3880. return fieldType;
  3881. fieldInstance->SetResolvedType(resolvedType);
  3882. if (field->mIsStatic)
  3883. {
  3884. }
  3885. else if (fieldInstance->mDataIdx >= 0)
  3886. {
  3887. }
  3888. else
  3889. {
  3890. BF_ASSERT(typeInstance->IsIncomplete());
  3891. }
  3892. return resolvedType;
  3893. }
  3894. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3895. {
  3896. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3897. auto fieldType = fieldInstance->GetResolvedType();
  3898. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3899. {
  3900. int fieldIdx = 0;
  3901. int fieldCount = 0;
  3902. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  3903. fieldIdx--;
  3904. int count = fieldCount;
  3905. if (fieldIdx == -1)
  3906. count = 1;
  3907. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3908. auto thisVariable = GetThisVariable();
  3909. if (thisVariable != NULL)
  3910. {
  3911. for (int i = 0; i < count; i++)
  3912. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  3913. }
  3914. }
  3915. }
  3916. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3917. {
  3918. if (fieldInstance->mCustomAttributes == NULL)
  3919. return false;
  3920. auto fieldDef = fieldInstance->GetFieldDef();
  3921. if (!fieldDef->mIsStatic)
  3922. return false;
  3923. bool isThreadLocal = false;
  3924. if (fieldInstance->mCustomAttributes != NULL)
  3925. {
  3926. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3927. {
  3928. if (customAttr.mType->ToTypeInstance()->IsInstanceOf(mCompiler->mThreadStaticAttributeTypeDef))
  3929. return true;
  3930. }
  3931. }
  3932. return false;
  3933. }
  3934. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  3935. {
  3936. if (fieldDef == NULL)
  3937. fieldDef = fieldInstance->GetFieldDef();
  3938. if (fieldType == NULL)
  3939. fieldType = fieldInstance->GetResolvedType();
  3940. if (initializer == NULL)
  3941. {
  3942. if (fieldDef == NULL)
  3943. return BfTypedValue();
  3944. initializer = fieldDef->GetInitializer();
  3945. }
  3946. BfTypedValue staticVarRef;
  3947. BfTypedValue result;
  3948. if (initializer == NULL)
  3949. {
  3950. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3951. }
  3952. else
  3953. {
  3954. if (mCompiler->mIsResolveOnly)
  3955. {
  3956. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  3957. {
  3958. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3959. sourceClassifier->VisitChildNoRef(initializer);
  3960. }
  3961. }
  3962. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3963. {
  3964. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3965. BfConstResolver constResolver(this);
  3966. constResolver.Resolve(initializer);
  3967. return GetDefaultTypedValue(fieldType);
  3968. }
  3969. else if (mCurTypeInstance->IsUnspecializedTypeVariation())
  3970. {
  3971. return GetDefaultTypedValue(fieldType);
  3972. }
  3973. else if (fieldDef->mIsConst)
  3974. {
  3975. int ceExecuteId = -1;
  3976. if (mCompiler->mCeMachine != NULL)
  3977. ceExecuteId = mCompiler->mCeMachine->mExecuteId;
  3978. BfTypeState typeState;
  3979. typeState.mType = mCurTypeInstance;
  3980. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3981. typeState.mCurFieldDef = fieldDef;
  3982. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3983. BfConstResolver constResolver(this);
  3984. if (fieldType->IsVar())
  3985. return constResolver.Resolve(initializer);
  3986. else
  3987. {
  3988. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  3989. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  3990. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  3991. {
  3992. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  3993. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  3994. resolveFlags = BfConstResolveFlag_NoCast;
  3995. }
  3996. UpdateSrcPos(initializer);
  3997. auto result = constResolver.Resolve(initializer, fieldType, resolveFlags);
  3998. if ((mCompiler->mCeMachine != NULL) && (fieldInstance != NULL))
  3999. {
  4000. if (mCompiler->mCeMachine->mExecuteId != ceExecuteId)
  4001. fieldInstance->mHadConstEval = true;
  4002. }
  4003. return result;
  4004. }
  4005. }
  4006. BfExprEvaluator exprEvaluator(this);
  4007. if (doStore)
  4008. {
  4009. staticVarRef = ReferenceStaticField(fieldInstance);
  4010. exprEvaluator.mReceivingValue = &staticVarRef;
  4011. }
  4012. if (fieldType->IsVar())
  4013. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4014. else
  4015. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4016. if (doStore)
  4017. {
  4018. if (exprEvaluator.mReceivingValue == NULL)
  4019. doStore = false; // Already stored
  4020. }
  4021. }
  4022. if (fieldInstance != NULL)
  4023. MarkFieldInitialized(fieldInstance);
  4024. if ((doStore) && (result))
  4025. {
  4026. if (fieldInstance->mResolvedType->IsUndefSizedArray())
  4027. {
  4028. if ((!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mFastFinish))
  4029. AssertErrorState();
  4030. }
  4031. else
  4032. {
  4033. result = LoadValue(result);
  4034. if (!result.mType->IsValuelessType())
  4035. mBfIRBuilder->CreateAlignedStore(result.mValue, staticVarRef.mValue, result.mType->mAlign);
  4036. }
  4037. }
  4038. return result;
  4039. }
  4040. void BfModule::AppendedObjectInit(BfFieldInstance* fieldInst)
  4041. {
  4042. BfExprEvaluator exprEvaluator(this);
  4043. bool failed = false;
  4044. auto fieldDef = fieldInst->GetFieldDef();
  4045. auto initializer = fieldDef->GetInitializer();
  4046. BfResolvedArgs resolvedArgs;
  4047. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(initializer))
  4048. {
  4049. bool isDot = false;
  4050. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  4051. isDot = (memberRefExpr->mTarget == NULL) && (memberRefExpr->mMemberName == NULL);
  4052. if (!isDot)
  4053. {
  4054. auto resolvedType = ResolveTypeRef(invocationExpr->mTarget, {});
  4055. if ((resolvedType == NULL) || (resolvedType != fieldInst->mResolvedType))
  4056. failed = true;
  4057. }
  4058. SetAndRestoreValue<BfType*> prevExpectingType(exprEvaluator.mExpectingType, fieldInst->mResolvedType);
  4059. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  4060. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  4061. }
  4062. else if (initializer != NULL)
  4063. {
  4064. GetFieldInitializerValue(fieldInst);
  4065. failed = true;
  4066. }
  4067. if (failed)
  4068. Fail("Append fields can only be initialized with a call to their constructor", initializer);
  4069. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  4070. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4071. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4072. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  4073. auto fieldTypeInst = fieldInst->mResolvedType->ToTypeInstance();
  4074. BfIRValue fieldAddr;
  4075. if (fieldDef->mIsStatic)
  4076. {
  4077. fieldAddr = ReferenceStaticField(fieldInst).mValue;
  4078. }
  4079. else
  4080. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  4081. auto thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  4082. auto indexVal = BfTypedValue(CreateAlloca(intType), CreateRefType(intType));
  4083. auto intThisVal = mBfIRBuilder->CreatePtrToInt(thisValue.mValue, (intType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  4084. auto curValPtr = mBfIRBuilder->CreateAdd(intThisVal, GetConstValue(fieldTypeInst->mInstSize, intType));
  4085. mBfIRBuilder->CreateStore(curValPtr, indexVal.mValue);
  4086. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 0);
  4087. auto vDataRef = CreateClassVDataGlobal(fieldInst->mResolvedType->ToTypeInstance());
  4088. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  4089. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  4090. mBfIRBuilder->CreateStore(srcVal, destAddr);
  4091. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  4092. {
  4093. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4094. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4095. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(thisValue.mValue, ptrType);
  4096. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_AppendAlloc), thisFlagsPtr);
  4097. }
  4098. exprEvaluator.MatchConstructor(fieldDef->GetNameNode(), NULL, thisValue, fieldInst->mResolvedType->ToTypeInstance(), resolvedArgs, false, true, &indexVal);
  4099. }
  4100. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  4101. {
  4102. }
  4103. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  4104. {
  4105. PopulateType(classType);
  4106. if (isInterfacePass)
  4107. {
  4108. for (auto ifaceInst : classType->mInterfaces)
  4109. {
  4110. if (exChecks->Contains(ifaceInst.mInterfaceType))
  4111. continue;
  4112. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  4113. continue;
  4114. if (ifaceInst.mDeclaringType->IsExtension())
  4115. {
  4116. bool needsExCheck = false;
  4117. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  4118. {
  4119. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  4120. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  4121. {
  4122. exChecks->push_back(ifaceInst.mInterfaceType);
  4123. continue;
  4124. }
  4125. else
  4126. {
  4127. // We can only do an 'exCheck' if we're actually going to slot this interface
  4128. }
  4129. }
  4130. }
  4131. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  4132. }
  4133. }
  4134. else
  4135. {
  4136. outVals->push_back(classType->mTypeId);
  4137. }
  4138. if (classType->mBaseType != NULL)
  4139. {
  4140. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  4141. }
  4142. }
  4143. void BfModule::CreateDynamicCastMethod()
  4144. {
  4145. auto objType = mContext->mBfObjectType;
  4146. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  4147. {
  4148. // The main reason to punt on this method for ResolveOnly is because types can be created
  4149. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  4150. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  4151. // remove this punt when we recycle typeId's
  4152. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  4153. mCurMethodState->mHadReturn = true;
  4154. return;
  4155. }
  4156. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  4157. auto func = mCurMethodState->mIRFunction;
  4158. auto thisValue = mBfIRBuilder->GetArgument(0);
  4159. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  4160. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4161. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  4162. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  4163. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  4164. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  4165. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  4166. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4167. SizedArray<int, 8> typeMatches;
  4168. SizedArray<BfTypeInstance*, 8> exChecks;
  4169. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  4170. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  4171. {
  4172. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  4173. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  4174. BfTypeVector genericArgs;
  4175. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  4176. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  4177. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef->GetDefinition(), genericArgs, BfPopulateType_Declaration);
  4178. typeMatches.push_back(unboundType->mTypeId);
  4179. }
  4180. if (mCurTypeInstance->IsBoxed())
  4181. {
  4182. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  4183. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  4184. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  4185. if (innerType->IsTypedPrimitive())
  4186. {
  4187. auto underlyingType = innerType->GetUnderlyingType();
  4188. typeMatches.push_back(underlyingType->mTypeId);
  4189. }
  4190. auto innerTypeInst = innerType->ToTypeInstance();
  4191. if ((innerTypeInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef)) ||
  4192. (innerTypeInst->IsInstanceOf(mCompiler->mPointerTTypeDef)) ||
  4193. (innerTypeInst->IsInstanceOf(mCompiler->mMethodRefTypeDef)))
  4194. {
  4195. PopulateType(innerTypeInst);
  4196. //TODO: What case was this supposed to handle?
  4197. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  4198. }
  4199. }
  4200. auto curBlock = mBfIRBuilder->GetInsertBlock();
  4201. BfIRValue vDataPtr;
  4202. if (!exChecks.empty())
  4203. {
  4204. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4205. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  4206. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  4207. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4208. }
  4209. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  4210. for (auto typeMatch : typeMatches)
  4211. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  4212. Array<BfIRValue> incomingFalses;
  4213. for (auto ifaceTypeInst : exChecks)
  4214. {
  4215. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  4216. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  4217. mBfIRBuilder->SetInsertPoint(nextBB);
  4218. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  4219. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4220. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4221. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4222. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  4223. incomingFalses.push_back(nextBB);
  4224. }
  4225. mBfIRBuilder->AddBlock(trueBB);
  4226. mBfIRBuilder->SetInsertPoint(trueBB);
  4227. mBfIRBuilder->CreateBr(exitBB);
  4228. mBfIRBuilder->AddBlock(exitBB);
  4229. mBfIRBuilder->SetInsertPoint(exitBB);
  4230. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  4231. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  4232. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  4233. for (auto incomingFalseBlock : incomingFalses)
  4234. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  4235. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  4236. mBfIRBuilder->CreateRet(phi);
  4237. mCurMethodState->mHadReturn = true;
  4238. }
  4239. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  4240. {
  4241. BfExprEvaluator exprEvaluator(this);
  4242. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  4243. auto typeInst = rightValue.mType->ToTypeInstance();
  4244. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  4245. BfTypedValue result = exprEvaluator.GetResult();
  4246. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  4247. {
  4248. // Fail?
  4249. }
  4250. if ((result) && (!result.mType->IsVar()))
  4251. {
  4252. auto nextBB = mBfIRBuilder->CreateBlock("next");
  4253. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  4254. mBfIRBuilder->AddBlock(nextBB);
  4255. mBfIRBuilder->SetInsertPoint(nextBB);
  4256. }
  4257. }
  4258. void BfModule::CreateFakeCallerMethod(const String& funcName)
  4259. {
  4260. if (mCurMethodInstance->mHasFailed)
  4261. return;
  4262. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  4263. return;
  4264. BF_ASSERT(mCurMethodInstance->mIRFunction);
  4265. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  4266. SizedArray<BfIRType, 4> paramTypes;
  4267. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  4268. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  4269. mBfIRBuilder->SetActiveFunction(func);
  4270. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  4271. mBfIRBuilder->SetInsertPoint(entryBlock);
  4272. BfMethodState methodState;
  4273. methodState.mIRHeadBlock = entryBlock;
  4274. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4275. SizedArray<BfIRValue, 8> args;
  4276. BfExprEvaluator exprEvaluator(this);
  4277. if (mCurMethodInstance->GetStructRetIdx() == 0)
  4278. {
  4279. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4280. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4281. }
  4282. if (mCurMethodInstance->HasThis())
  4283. {
  4284. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  4285. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  4286. }
  4287. if (mCurMethodInstance->GetStructRetIdx() == 1)
  4288. {
  4289. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4290. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4291. }
  4292. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  4293. {
  4294. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  4295. if (paramType->IsValuelessType())
  4296. continue;
  4297. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  4298. }
  4299. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  4300. mBfIRBuilder->CreateRetVoid();
  4301. }
  4302. void BfModule::CreateDelegateEqualsMethod()
  4303. {
  4304. if (mBfIRBuilder->mIgnoreWrites)
  4305. return;
  4306. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4307. if (refNode == NULL)
  4308. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4309. UpdateSrcPos(refNode);
  4310. SetIllegalSrcPos();
  4311. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4312. auto resultVal = CreateAlloca(boolType);
  4313. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4314. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4315. auto delegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  4316. mBfIRBuilder->PopulateType(delegateType);
  4317. BfExprEvaluator exprEvaluator(this);
  4318. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4319. BfTypedValue lhsDelegate = BfTypedValue(mBfIRBuilder->CreateBitCast(leftTypedVal.mValue, mBfIRBuilder->MapType(delegateType)), delegateType);
  4320. BfTypedValue rhsDelegate = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4321. rhsDelegate = LoadValue(rhsDelegate);
  4322. BfTypedValue rightTypedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(rhsDelegate.mValue, mBfIRBuilder->MapType(mCurTypeInstance)), mCurTypeInstance);
  4323. auto& targetFieldInstance = delegateType->mFieldInstances[0];
  4324. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(lhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4325. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4326. leftValue = LoadValue(leftValue);
  4327. rightValue = LoadValue(rightValue);
  4328. EmitEquals(leftValue, rightValue, exitBB, false);
  4329. bool hadComparison = false;
  4330. for (auto& fieldRef : mCurTypeInstance->mFieldInstances)
  4331. {
  4332. BfFieldInstance* fieldInstance = &fieldRef;
  4333. if (fieldInstance->mDataOffset == -1)
  4334. continue;
  4335. auto fieldType = fieldInstance->mResolvedType;
  4336. if (fieldType->IsValuelessType())
  4337. continue;
  4338. if (fieldType->IsVar())
  4339. continue;
  4340. if (fieldType->IsMethodRef())
  4341. continue;
  4342. if (fieldType->IsRef())
  4343. fieldType = CreatePointerType(fieldType->GetUnderlyingType());
  4344. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(leftTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4345. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rightTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4346. if (!fieldInstance->mResolvedType->IsComposite())
  4347. {
  4348. leftValue = LoadValue(leftValue);
  4349. rightValue = LoadValue(rightValue);
  4350. }
  4351. EmitEquals(leftValue, rightValue, exitBB, false);
  4352. }
  4353. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4354. mBfIRBuilder->CreateBr(exitBB);
  4355. mBfIRBuilder->AddBlock(exitBB);
  4356. mBfIRBuilder->SetInsertPoint(exitBB);
  4357. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4358. ClearLifetimeEnds();
  4359. mBfIRBuilder->CreateRet(loadedResult);
  4360. mCurMethodState->mHadReturn = true;
  4361. }
  4362. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  4363. {
  4364. if (mCurMethodInstance->mIsUnspecialized)
  4365. return;
  4366. if (mBfIRBuilder->mIgnoreWrites)
  4367. return;
  4368. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  4369. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  4370. bool isValid = true;
  4371. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4372. if (compareType->IsValuelessType())
  4373. {
  4374. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4375. return;
  4376. }
  4377. if (compareType->IsTypedPrimitive())
  4378. {
  4379. BfExprEvaluator exprEvaluator(this);
  4380. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  4381. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  4382. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  4383. mBfIRBuilder->CreateRet(cmpResult);
  4384. return;
  4385. }
  4386. auto compareDType = compareType->ToDependedType();
  4387. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  4388. if (compareTypeInst != NULL)
  4389. {
  4390. if (compareType->IsPrimitiveType())
  4391. compareTypeInst = GetWrappedStructType(compareType);
  4392. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  4393. {
  4394. isValid = false;
  4395. }
  4396. mBfIRBuilder->PopulateType(compareTypeInst);
  4397. }
  4398. if (!isValid)
  4399. {
  4400. ClearLifetimeEnds();
  4401. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4402. return;
  4403. }
  4404. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  4405. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4406. if (refNode == NULL)
  4407. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4408. UpdateSrcPos(refNode);
  4409. SetIllegalSrcPos();
  4410. auto resultVal = CreateAlloca(boolType);
  4411. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4412. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4413. if (compareType->IsValuelessType())
  4414. {
  4415. // Always equal, nothing to do
  4416. }
  4417. else if (compareType->IsSizedArray())
  4418. {
  4419. auto sizedArrayType = (BfSizedArrayType*)compareType;
  4420. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  4421. {
  4422. BfTypedValue result;
  4423. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index, true);
  4424. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4425. if (!result.mType->IsValueType())
  4426. result = LoadValue(result);
  4427. return result;
  4428. };
  4429. if (sizedArrayType->mElementCount > 6)
  4430. {
  4431. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4432. auto itr = CreateAlloca(intPtrType);
  4433. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  4434. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  4435. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  4436. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  4437. mBfIRBuilder->CreateBr(loopBB);
  4438. mBfIRBuilder->SetInsertPoint(loopBB);
  4439. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  4440. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  4441. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  4442. mBfIRBuilder->SetInsertPoint(bodyBB);
  4443. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  4444. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  4445. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4446. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  4447. mBfIRBuilder->CreateStore(incValue, itr);
  4448. mBfIRBuilder->CreateBr(loopBB);
  4449. mBfIRBuilder->SetInsertPoint(doneBB);
  4450. }
  4451. else
  4452. {
  4453. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  4454. {
  4455. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4456. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4457. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4458. }
  4459. }
  4460. }
  4461. else if (compareType->IsMethodRef())
  4462. {
  4463. auto methodRefType = (BfMethodRefType*)compareType;
  4464. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  4465. BfExprEvaluator exprEvaluator(this);
  4466. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4467. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4468. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  4469. // values for the same method reference -- they will always refer back to the same local variables.
  4470. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  4471. if (dataIdx != -1)
  4472. {
  4473. bool failed = false;
  4474. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  4475. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  4476. BF_ASSERT(!failed);
  4477. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4478. }
  4479. }
  4480. else if (compareTypeInst->IsEnum())
  4481. {
  4482. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4483. BfExprEvaluator exprEvaluator(this);
  4484. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4485. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4486. auto dscrType = compareTypeInst->GetDiscriminatorType();
  4487. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  4488. leftValue = LoadValue(leftValue);
  4489. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  4490. rightValue = LoadValue(rightValue);
  4491. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  4492. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  4493. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4494. int enumCount = 0;
  4495. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4496. {
  4497. BfFieldInstance* fieldInstance = &fieldRef;
  4498. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4499. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4500. {
  4501. enumCount = -fieldInstance->mDataIdx;
  4502. }
  4503. }
  4504. if (enumCount > 0)
  4505. {
  4506. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  4507. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  4508. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4509. {
  4510. BfFieldInstance* fieldInstance = &fieldRef;
  4511. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4512. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4513. {
  4514. int enumIdx = -fieldInstance->mDataIdx - 1;
  4515. if (fieldInstance->mResolvedType->mSize == 0)
  4516. {
  4517. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  4518. }
  4519. else
  4520. {
  4521. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  4522. mBfIRBuilder->SetInsertPoint(caseBlock);
  4523. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  4524. BfTypedValue leftTuple;
  4525. BfTypedValue rightTuple;
  4526. if (leftPayload.IsAddr())
  4527. {
  4528. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4529. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4530. }
  4531. else
  4532. {
  4533. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4534. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4535. }
  4536. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  4537. mBfIRBuilder->CreateBr(matchedBlock);
  4538. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  4539. }
  4540. }
  4541. }
  4542. mBfIRBuilder->AddBlock(matchedBlock);
  4543. mBfIRBuilder->SetInsertPoint(matchedBlock);
  4544. }
  4545. }
  4546. else if (compareTypeInst->IsUnion())
  4547. {
  4548. auto innerType = compareTypeInst->GetUnionInnerType();
  4549. if (!innerType->IsValuelessType())
  4550. {
  4551. BfExprEvaluator exprEvaluator(this);
  4552. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4553. leftTypedVal = AggregateSplat(leftTypedVal);
  4554. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  4555. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4556. rightTypedVal = AggregateSplat(rightTypedVal);
  4557. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  4558. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  4559. }
  4560. }
  4561. else
  4562. {
  4563. BfExprEvaluator exprEvaluator(this);
  4564. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4565. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4566. bool hadComparison = false;
  4567. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4568. {
  4569. BfFieldInstance* fieldInstance = &fieldRef;
  4570. if (fieldInstance->mDataOffset == -1)
  4571. continue;
  4572. if (fieldInstance->mResolvedType->IsValuelessType())
  4573. continue;
  4574. if (fieldInstance->mResolvedType->IsVar())
  4575. continue;
  4576. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4577. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4578. if (!fieldInstance->mResolvedType->IsComposite())
  4579. {
  4580. leftValue = LoadValue(leftValue);
  4581. rightValue = LoadValue(rightValue);
  4582. }
  4583. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4584. }
  4585. auto baseTypeInst = compareTypeInst->mBaseType;
  4586. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  4587. {
  4588. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  4589. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  4590. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4591. }
  4592. }
  4593. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4594. mBfIRBuilder->CreateBr(exitBB);
  4595. mBfIRBuilder->AddBlock(exitBB);
  4596. mBfIRBuilder->SetInsertPoint(exitBB);
  4597. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4598. ClearLifetimeEnds();
  4599. mBfIRBuilder->CreateRet(loadedResult);
  4600. mCurMethodState->mHadReturn = true;
  4601. }
  4602. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  4603. {
  4604. if (mBfIRBuilder->mIgnoreWrites)
  4605. return mBfIRBuilder->GetFakeVal();
  4606. PopulateType(typeInstance, mIsComptimeModule ? BfPopulateType_Data : BfPopulateType_DataAndMethods);
  4607. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4608. if (mIsComptimeModule)
  4609. {
  4610. auto idVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, typeInstance->mTypeId);
  4611. return mBfIRBuilder->CreateIntToPtr(idVal, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4612. }
  4613. BfIRValue* globalVariablePtr = NULL;
  4614. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  4615. int numElements = 1;
  4616. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  4617. {
  4618. numElements += mCompiler->mMaxInterfaceSlots;
  4619. auto maxIFaceVirtIdx = 0;
  4620. if (!typeInstance->IsInterface())
  4621. {
  4622. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4623. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4624. numElements += typeInstance->GetOrigVTableSize();
  4625. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  4626. if (typeInstance->mHotTypeData != NULL)
  4627. {
  4628. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4629. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4630. }
  4631. numElements += ifaceMethodLen;
  4632. }
  4633. if (outNumElements != NULL)
  4634. *outNumElements = numElements;
  4635. }
  4636. StringT<128> classVDataName;
  4637. String memberName = "sBfClassVData";
  4638. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  4639. {
  4640. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  4641. memberName += "_";
  4642. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  4643. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  4644. }
  4645. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  4646. if (outMangledName != NULL)
  4647. *outMangledName = classVDataName;
  4648. /*if (itr != mClassVDataRefs.end())
  4649. {
  4650. globalVariable = itr->second;
  4651. }*/
  4652. BfIRValue globalVariable;
  4653. if (globalVariablePtr != NULL)
  4654. {
  4655. globalVariable = *globalVariablePtr;
  4656. }
  4657. else
  4658. {
  4659. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4660. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4661. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4662. arrayType,
  4663. true,
  4664. BfIRLinkageType_External,
  4665. BfIRValue(),
  4666. classVDataName);
  4667. mClassVDataRefs[typeInstance] = globalVariable;
  4668. }
  4669. return globalVariable;
  4670. }
  4671. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4672. {
  4673. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4674. if (mIsComptimeModule)
  4675. return mBfIRBuilder->Comptime_GetBfType(typeInstance->mTypeId, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4676. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4677. }
  4678. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4679. {
  4680. if (mBfIRBuilder->mIgnoreWrites)
  4681. return mBfIRBuilder->GetFakeVal();
  4682. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4683. BF_ASSERT(numElements >= 0);
  4684. if (numElements <= 0)
  4685. return BfIRValue();
  4686. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4687. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4688. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4689. BF_ASSERT(declTypeInst == implTypeInst);
  4690. else
  4691. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4692. if (declTypeInst != implTypeInst)
  4693. {
  4694. BfTypeInstance* highestImpl = declTypeInst;
  4695. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4696. {
  4697. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4698. break; // Start of an ext entry for another type
  4699. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4700. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4701. highestImpl = checkImplTypeInst;
  4702. }
  4703. if (highestImpl != implTypeInst)
  4704. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4705. }
  4706. BfVDataExtEntry mapEntry;
  4707. mapEntry.mDeclTypeInst = declTypeInst;
  4708. mapEntry.mImplTypeInst = implTypeInst;
  4709. BfIRValue* irValuePtr = NULL;
  4710. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4711. return *irValuePtr;
  4712. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4713. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4714. StringT<512> classVDataName;
  4715. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4716. if (declTypeInst != implTypeInst)
  4717. {
  4718. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4719. }
  4720. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4721. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4722. SizedArray<BfIRValue, 32> vData;
  4723. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4724. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4725. {
  4726. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4727. break; // Start of an ext entry for another type
  4728. BfIRValue vValue;
  4729. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4730. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4731. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4732. {
  4733. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4734. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4735. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4736. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4737. {
  4738. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4739. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4740. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4741. vValue = funcPtr;
  4742. }
  4743. }
  4744. if (!vValue)
  4745. vValue = voidPtrNull;
  4746. vData.Add(vValue);
  4747. }
  4748. BF_ASSERT((int)vData.size() == numElements);
  4749. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4750. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4751. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4752. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4753. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4754. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, vData);
  4755. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4756. mClassVDataExtRefs[mapEntry] = globalVariable;
  4757. return globalVariable;
  4758. }
  4759. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  4760. {
  4761. if (mBfIRBuilder->mIgnoreWrites)
  4762. {
  4763. return mBfIRBuilder->CreateTypeOf(type);
  4764. }
  4765. if (mIsComptimeModule)
  4766. {
  4767. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4768. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4769. return mBfIRBuilder->Comptime_GetReflectType(type->mTypeId, mBfIRBuilder->MapType(typeTypeInst));
  4770. }
  4771. PopulateType(type);
  4772. BfIRValue globalVariable;
  4773. BfIRValue* globalVariablePtr = NULL;
  4774. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  4775. {
  4776. if (*globalVariablePtr)
  4777. return mBfIRBuilder->CreateTypeOf(type, *globalVariablePtr);
  4778. }
  4779. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4780. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4781. auto typeInstance = type->ToTypeInstance();
  4782. StringT<4096> typeDataName;
  4783. if (typeInstance != NULL)
  4784. {
  4785. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4786. }
  4787. else
  4788. {
  4789. typeDataName += "sBfTypeData.";
  4790. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  4791. }
  4792. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  4793. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  4794. mBfIRBuilder->SetReflectTypeData(mBfIRBuilder->MapType(type), globalVariable);
  4795. mTypeDataRefs[type] = globalVariable;
  4796. return mBfIRBuilder->CreateTypeOf(type, globalVariable);
  4797. }
  4798. void BfModule::EncodeAttributeData(BfTypeInstance* typeInstance, BfType* argType, BfIRValue arg, SizedArrayImpl<uint8>& data, Dictionary<int, int>& usedStringIdMap)
  4799. {
  4800. #define PUSH_INT8(val) data.push_back((uint8)val)
  4801. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4802. #define PUSH_INT32(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); data.push_back((val >> 16) & 0xFF); data.push_back((val >> 24) & 0xFF); }
  4803. #define PUSH_INT64(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); data.push_back((val >> 16) & 0xFF); data.push_back((val >> 24) & 0xFF); \
  4804. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4805. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4806. bool handled = false;
  4807. if (constant == NULL)
  4808. {
  4809. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  4810. return;
  4811. }
  4812. if (argType->IsObject())
  4813. {
  4814. if (argType->IsInstanceOf(mCompiler->mStringTypeDef))
  4815. {
  4816. int stringId = constant->mInt32;
  4817. int* orderedIdPtr;
  4818. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4819. {
  4820. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4821. }
  4822. GetStringObjectValue(stringId, true, true);
  4823. PUSH_INT8(0xFF); // String
  4824. PUSH_INT32(*orderedIdPtr);
  4825. return;
  4826. }
  4827. }
  4828. if (argType->IsPointer())
  4829. {
  4830. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  4831. {
  4832. if (constant->mTypeCode == BfTypeCode_StringId)
  4833. {
  4834. int stringId = constant->mInt32;
  4835. int* orderedIdPtr;
  4836. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4837. {
  4838. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4839. }
  4840. GetStringObjectValue(stringId, true, true);
  4841. PUSH_INT8(0xFF); // String
  4842. PUSH_INT32(*orderedIdPtr);
  4843. return;
  4844. }
  4845. }
  4846. }
  4847. PUSH_INT8(constant->mTypeCode);
  4848. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4849. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4850. (constant->mTypeCode == BfTypeCode_Double))
  4851. {
  4852. PUSH_INT64(constant->mInt64);
  4853. }
  4854. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4855. (constant->mTypeCode == BfTypeCode_UInt32) ||
  4856. (constant->mTypeCode == BfTypeCode_Char32))
  4857. {
  4858. PUSH_INT32(constant->mInt32);
  4859. }
  4860. else if (constant->mTypeCode == BfTypeCode_Float)
  4861. {
  4862. float val = (float)constant->mDouble;
  4863. PUSH_INT32(*(int*)&val);
  4864. }
  4865. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4866. (constant->mTypeCode == BfTypeCode_UInt16) ||
  4867. (constant->mTypeCode == BfTypeCode_Char16))
  4868. {
  4869. PUSH_INT16(constant->mInt16);
  4870. }
  4871. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4872. (constant->mTypeCode == BfTypeCode_UInt8) ||
  4873. (constant->mTypeCode == BfTypeCode_Boolean) ||
  4874. (constant->mTypeCode == BfTypeCode_Char8))
  4875. {
  4876. PUSH_INT8(constant->mInt8);
  4877. }
  4878. else if (constant->mConstType == BfConstType_TypeOf)
  4879. {
  4880. auto typeOf = (BfTypeOf_Const*)constant;
  4881. PUSH_INT32(typeOf->mType->mTypeId);
  4882. }
  4883. else if (constant->mConstType == BfConstType_AggZero)
  4884. {
  4885. for (int i = 0; i < argType->mSize; i++)
  4886. data.Add(0);
  4887. }
  4888. // else if (constant->mConstType == BfConstType_Agg)
  4889. // {
  4890. // BF_ASSERT(argType->IsComposite());
  4891. // if (argType->IsSizedArray())
  4892. // {
  4893. // auto argSizedArrayType = (BfSizedArrayType*)argType;
  4894. // }
  4895. // else
  4896. // {
  4897. // auto argTypeInstance = argType->ToTypeInstance();
  4898. // }
  4899. // }
  4900. else
  4901. {
  4902. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  4903. }
  4904. }
  4905. BfIRValue BfModule::CreateFieldData(BfFieldInstance* fieldInstance, int customAttrIdx)
  4906. {
  4907. bool isComptimeArg = mBfIRBuilder->mIgnoreWrites;
  4908. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4909. auto typeInstance = fieldInstance->mOwner;
  4910. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  4911. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4912. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  4913. BfType* typeIdType = intType;
  4914. BfTypeInstance* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef)->ToTypeInstance();
  4915. BfIRValue emptyValueType = mBfIRBuilder->mIgnoreWrites ?
  4916. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>()) :
  4917. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>());
  4918. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, !mIsComptimeModule);
  4919. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  4920. int typeId = 0;
  4921. auto fieldType = fieldInstance->GetResolvedType();
  4922. if (fieldType->IsGenericParam())
  4923. {
  4924. //TODO:
  4925. }
  4926. else
  4927. typeId = fieldType->mTypeId;
  4928. BfFieldFlags fieldFlags = (BfFieldFlags)0;
  4929. if (fieldDef->mProtection == BfProtection_Protected)
  4930. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Protected);
  4931. if (fieldDef->mProtection == BfProtection_Public)
  4932. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Public);
  4933. if (fieldDef->mIsStatic)
  4934. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Static);
  4935. if (fieldDef->mIsConst)
  4936. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Const);
  4937. if (fieldDef->IsEnumCaseEntry())
  4938. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_EnumCase);
  4939. if (fieldDef->mIsReadOnly)
  4940. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_ReadOnly);
  4941. if (fieldInstance->IsAppendedObject())
  4942. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Appended);
  4943. BfIRValue constValue;
  4944. BfIRValue constValue2;
  4945. if (fieldInstance->GetFieldDef()->mIsConst)
  4946. {
  4947. if (fieldInstance->mConstIdx != -1)
  4948. {
  4949. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4950. uint64 val = constant->mUInt64;
  4951. if (constant->mTypeCode == BfTypeCode_Float)
  4952. {
  4953. float f = (float)*(double*)&val;
  4954. val = *(uint32*)&f;
  4955. }
  4956. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  4957. if (is32Bit)
  4958. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val >> 32);
  4959. }
  4960. }
  4961. else if (fieldInstance->GetFieldDef()->mIsStatic)
  4962. {
  4963. BfTypedValue refVal;
  4964. if (!mIsComptimeModule) // This can create circular reference issues for a `Self` static
  4965. refVal = ReferenceStaticField(fieldInstance);
  4966. if (refVal.mValue.IsConst())
  4967. {
  4968. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  4969. if (constant->mConstType == BfConstType_GlobalVar)
  4970. {
  4971. auto globalVar = (BfGlobalVar*)constant;
  4972. if (globalVar->mName[0] == '#')
  4973. refVal = BfTypedValue();
  4974. }
  4975. }
  4976. if (!isComptimeArg)
  4977. {
  4978. if (refVal.IsAddr())
  4979. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  4980. else if ((fieldInstance->IsAppendedObject()) && (refVal))
  4981. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  4982. }
  4983. }
  4984. if (!constValue)
  4985. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  4986. BfIRValue result;
  4987. if (is32Bit)
  4988. {
  4989. if (!constValue2)
  4990. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  4991. SizedArray<BfIRValue, 8> fieldVals =
  4992. {
  4993. emptyValueType,
  4994. fieldNameConst, // mName
  4995. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4996. constValue, // mData
  4997. constValue2, // mDataHi
  4998. GetConstValue(fieldFlags, shortType), // mFlags
  4999. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5000. };
  5001. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5002. result = isComptimeArg ?
  5003. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5004. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5005. }
  5006. else
  5007. {
  5008. SizedArray<BfIRValue, 8> fieldVals =
  5009. {
  5010. emptyValueType,
  5011. fieldNameConst, // mName
  5012. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5013. constValue, // mData
  5014. GetConstValue(fieldFlags, shortType), // mFlags
  5015. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5016. };
  5017. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5018. result = isComptimeArg ?
  5019. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5020. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5021. }
  5022. return result;
  5023. }
  5024. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  5025. {
  5026. if ((IsHotCompile()) && (!type->mDirty))
  5027. return BfIRValue();
  5028. BfIRValue* irValuePtr = NULL;
  5029. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  5030. {
  5031. return *irValuePtr;
  5032. }
  5033. BfTypeInstance* typeInstance = type->ToTypeInstance();
  5034. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  5035. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  5036. if (typeInstanceType == NULL)
  5037. {
  5038. AssertErrorState();
  5039. return BfIRValue();
  5040. }
  5041. BfIRValue typeTypeData;
  5042. int typeFlags = 0;
  5043. if (needsTypeData)
  5044. {
  5045. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  5046. BfTypeInstance* typeDataSource = NULL;
  5047. if (typeInstance != NULL)
  5048. {
  5049. if (typeInstance->IsUnspecializedType())
  5050. {
  5051. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  5052. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  5053. }
  5054. else if (typeInstance->IsArray())
  5055. {
  5056. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  5057. typeFlags |= BfTypeFlags_Array;
  5058. }
  5059. else if (typeInstance->IsGenericTypeInstance())
  5060. {
  5061. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  5062. typeFlags |= BfTypeFlags_SpecializedGeneric;
  5063. }
  5064. else
  5065. typeDataSource = typeInstanceTypeInstance;
  5066. }
  5067. else if (type->IsPointer())
  5068. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5069. else if (type->IsRef())
  5070. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5071. else if (type->IsSizedArray())
  5072. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5073. else if (type->IsConstExprValue())
  5074. typeDataSource = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5075. else if (type->IsGenericParam())
  5076. {
  5077. typeFlags |= BfTypeFlags_GenericParam;
  5078. typeDataSource = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5079. }
  5080. else
  5081. typeDataSource = mContext->mBfTypeType;
  5082. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type) && (!mIsComptimeModule))
  5083. {
  5084. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  5085. }
  5086. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  5087. }
  5088. else
  5089. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  5090. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5091. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5092. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5093. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5094. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5095. BfType* typeIdType = intType;
  5096. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  5097. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  5098. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  5099. auto voidPtrNull = GetDefaultValue(voidPtrType);
  5100. SizedArray<BfIRValue, 4> typeValueParams;
  5101. GetConstClassValueParam(typeTypeData, typeValueParams);
  5102. FixConstValueParams(mContext->mBfObjectType, typeValueParams);
  5103. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5104. StringT<512> typeDataName;
  5105. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  5106. {
  5107. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  5108. if (typeInstance->mTypeDef->IsGlobalsContainer())
  5109. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  5110. }
  5111. else
  5112. {
  5113. typeDataName += "sBfTypeData.";
  5114. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  5115. }
  5116. int typeCode = BfTypeCode_None;
  5117. if (typeInstance != NULL)
  5118. {
  5119. BF_ASSERT((type->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || mIsComptimeModule);
  5120. typeCode = typeInstance->mTypeDef->mTypeCode;
  5121. }
  5122. else if (type->IsPrimitiveType())
  5123. {
  5124. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  5125. typeCode = primType->mTypeDef->mTypeCode;
  5126. }
  5127. else if (type->IsPointer())
  5128. {
  5129. typeCode = BfTypeCode_Pointer;
  5130. typeFlags |= BfTypeFlags_Pointer;
  5131. }
  5132. else if (type->IsRef())
  5133. {
  5134. typeCode = BfTypeCode_Pointer;
  5135. typeFlags |= BfTypeFlags_Pointer;
  5136. }
  5137. if (type->IsObject())
  5138. {
  5139. typeFlags |= BfTypeFlags_Object;
  5140. if (typeInstance->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted)
  5141. {
  5142. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  5143. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  5144. typeFlags |= BfTypeFlags_HasDestructor;
  5145. }
  5146. }
  5147. if (type->IsStruct())
  5148. typeFlags |= BfTypeFlags_Struct;
  5149. if (type->IsInterface())
  5150. typeFlags |= BfTypeFlags_Interface;
  5151. if (type->IsBoxed())
  5152. {
  5153. typeFlags |= BfTypeFlags_Boxed;
  5154. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  5155. typeFlags |= BfTypeFlags_Pointer;
  5156. }
  5157. if (type->IsPrimitiveType())
  5158. typeFlags |= BfTypeFlags_Primitive;
  5159. if (type->IsTypedPrimitive())
  5160. typeFlags |= BfTypeFlags_TypedPrimitive;
  5161. if (type->IsTuple())
  5162. typeFlags |= BfTypeFlags_Tuple;
  5163. if (type->IsNullable())
  5164. typeFlags |= BfTypeFlags_Nullable;
  5165. if (type->IsSizedArray())
  5166. typeFlags |= BfTypeFlags_SizedArray;
  5167. if (type->IsConstExprValue())
  5168. typeFlags |= BfTypeFlags_ConstExpr;
  5169. if (type->IsSplattable())
  5170. typeFlags |= BfTypeFlags_Splattable;
  5171. if (type->IsUnion())
  5172. typeFlags |= BfTypeFlags_Union;
  5173. if (type->IsDelegate())
  5174. typeFlags |= BfTypeFlags_Delegate;
  5175. if (type->IsFunction())
  5176. typeFlags |= BfTypeFlags_Function;
  5177. if ((type->mDefineState != BfTypeDefineState_CETypeInit) && (type->WantsGCMarking()))
  5178. typeFlags |= BfTypeFlags_WantsMarking;
  5179. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsStatic))
  5180. typeFlags |= BfTypeFlags_Static;
  5181. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  5182. typeFlags |= BfTypeFlags_Abstract;
  5183. int virtSlotIdx = -1;
  5184. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5185. virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  5186. int memberDataOffset = 0;
  5187. if (type->IsInterface())
  5188. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  5189. else if (typeInstance != NULL)
  5190. {
  5191. for (auto& fieldInstance : typeInstance->mFieldInstances)
  5192. {
  5193. if (fieldInstance.mDataOffset != -1)
  5194. {
  5195. memberDataOffset = fieldInstance.mDataOffset;
  5196. break;
  5197. }
  5198. }
  5199. }
  5200. int boxedTypeId = 0;
  5201. if ((type->IsValueType()) || (type->IsWrappableType()))
  5202. {
  5203. auto boxedType = CreateBoxedType(type, false);
  5204. if ((boxedType != NULL) && (boxedType->mIsReified))
  5205. boxedTypeId = boxedType->mTypeId;
  5206. }
  5207. int stackCount = 0;
  5208. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  5209. {
  5210. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5211. if (typeOptions->mAllocStackTraceDepth != -1)
  5212. stackCount = BF_MIN(0xFF, BF_MAX(0x01, typeOptions->mAllocStackTraceDepth));
  5213. }
  5214. SizedArray<BfIRValue, 9> typeDataParams =
  5215. {
  5216. objectData,
  5217. GetConstValue(type->mSize, intType), // mSize
  5218. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5219. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  5220. GetConstValue(typeFlags, intType), // mTypeFlags
  5221. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  5222. GetConstValue(typeCode, byteType), // mTypeCode
  5223. GetConstValue(type->mAlign, byteType), // mAlign
  5224. GetConstValue(stackCount, byteType), // mAllocStackCountOverride
  5225. };
  5226. FixConstValueParams(mContext->mBfTypeType, typeDataParams);
  5227. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  5228. if (typeInstance == NULL)
  5229. {
  5230. BfIRValue typeDataVar;
  5231. if (needsTypeData)
  5232. {
  5233. if (type->IsPointer())
  5234. {
  5235. auto pointerType = (BfPointerType*)type;
  5236. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  5237. {
  5238. typeData,
  5239. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  5240. };
  5241. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5242. FixConstValueParams(reflectPointerType, pointerTypeDataParms);
  5243. auto pointerTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  5244. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  5245. BfIRLinkageType_External, pointerTypeData, typeDataName);
  5246. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5247. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5248. }
  5249. else if (type->IsRef())
  5250. {
  5251. auto refType = (BfRefType*)type;
  5252. SizedArray<BfIRValue, 3> refTypeDataParms =
  5253. {
  5254. typeData,
  5255. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  5256. GetConstValue((int8)refType->mRefKind, byteType),
  5257. };
  5258. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5259. FixConstValueParams(reflectRefType, refTypeDataParms);
  5260. auto refTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  5261. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  5262. BfIRLinkageType_External, refTypeData, typeDataName);
  5263. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5264. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5265. }
  5266. else if (type->IsSizedArray())
  5267. {
  5268. auto sizedArrayType = (BfSizedArrayType*)type;
  5269. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  5270. {
  5271. typeData,
  5272. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  5273. GetConstValue(sizedArrayType->mElementCount, intType)
  5274. };
  5275. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5276. FixConstValueParams(reflectSizedArrayType, sizedArrayTypeDataParms);
  5277. auto sizedArrayTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  5278. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  5279. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  5280. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5281. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5282. }
  5283. else if (type->IsConstExprValue())
  5284. {
  5285. auto constExprType = (BfConstExprValueType*)type;
  5286. SizedArray<BfIRValue, 3> constExprTypeDataParms =
  5287. {
  5288. typeData,
  5289. GetConstValue(constExprType->mType->mTypeId, typeIdType),
  5290. GetConstValue(constExprType->mValue.mInt64, longType)
  5291. };
  5292. auto reflectConstExprType = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5293. FixConstValueParams(reflectConstExprType, constExprTypeDataParms);
  5294. auto ConstExprTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectConstExprType, BfIRPopulateType_Full), constExprTypeDataParms);
  5295. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectConstExprType), true,
  5296. BfIRLinkageType_External, ConstExprTypeData, typeDataName);
  5297. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5298. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5299. }
  5300. else if (type->IsGenericParam())
  5301. {
  5302. auto genericParamType = (BfGenericParamType*)type;
  5303. SizedArray<BfIRValue, 3> genericParamTypeDataParms =
  5304. {
  5305. typeData
  5306. };
  5307. auto reflectGenericParamType = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5308. FixConstValueParams(reflectGenericParamType, genericParamTypeDataParms);
  5309. auto genericParamTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectGenericParamType, BfIRPopulateType_Full), genericParamTypeDataParms);
  5310. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectGenericParamType), true,
  5311. BfIRLinkageType_External, genericParamTypeData, typeDataName);
  5312. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5313. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5314. }
  5315. else
  5316. {
  5317. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  5318. BfIRLinkageType_External, typeData, typeDataName);
  5319. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5320. }
  5321. }
  5322. else
  5323. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5324. mTypeDataRefs[type] = typeDataVar;
  5325. return typeDataVar;
  5326. }
  5327. // Reserve position
  5328. mTypeDataRefs[typeInstance] = BfIRValue();
  5329. if ((typeInstance->IsReified()) && (!mIsComptimeModule))
  5330. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5331. BfTypeDef* typeDef = typeInstance->mTypeDef;
  5332. StringT<512> mangledName;
  5333. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  5334. if (!mIsComptimeModule)
  5335. {
  5336. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5337. {
  5338. auto methodDef = typeDef->mMethods[methodIdx];
  5339. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  5340. if (methodInstance == NULL)
  5341. continue;
  5342. if (typeInstance->IsUnspecializedType())
  5343. continue;
  5344. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5345. {
  5346. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  5347. {
  5348. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  5349. // We need to create an empty thunk for this chained method
  5350. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  5351. mBfIRBuilder->SetActiveFunction(func);
  5352. auto block = mBfIRBuilder->CreateBlock("entry", true);
  5353. mBfIRBuilder->SetInsertPoint(block);
  5354. mBfIRBuilder->CreateRetVoid();
  5355. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  5356. }
  5357. }
  5358. }
  5359. }
  5360. SizedArray<BfIRValue, 32> vData;
  5361. BfIRValue classVDataVar;
  5362. String classVDataName;
  5363. if (typeInstance->mSlotNum >= 0)
  5364. {
  5365. // For interfaces we ONLY emit the slot num
  5366. StringT<512> slotVarName;
  5367. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  5368. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  5369. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  5370. GetConstValue32(virtSlotIdx), slotVarName);
  5371. }
  5372. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  5373. {
  5374. int dynCastDataElems = 0;
  5375. int numElements = 1;
  5376. int vDataOfs = 1; // The number of intptrs before the iface slot map
  5377. numElements += mCompiler->mMaxInterfaceSlots;
  5378. if (!typeInstance->IsInterface())
  5379. {
  5380. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  5381. numElements += mCompiler->GetDynCastVDataCount();
  5382. numElements += typeInstance->mVirtualMethodTableSize;
  5383. }
  5384. int expectNumElements = 0;
  5385. if (!typeDef->mIsStatic)
  5386. {
  5387. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  5388. }
  5389. vData.push_back(BfIRValue()); // Type*
  5390. SizedArray<BfIRValue, 1> extVTableData;
  5391. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  5392. if (!typeInstance->IsInterface())
  5393. {
  5394. Array<int32> dynCastData;
  5395. if (typeInstance->IsBoxed())
  5396. {
  5397. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  5398. dynCastData.Add(underlyingType->mInheritanceId);
  5399. }
  5400. else
  5401. dynCastData.Add(typeInstance->mInheritanceId);
  5402. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  5403. dynCastData.Add(0);
  5404. dynCastData.Add(0);
  5405. auto checkTypeInst = typeInstance;
  5406. while (checkTypeInst != NULL)
  5407. {
  5408. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5409. {
  5410. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  5411. {
  5412. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  5413. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  5414. }
  5415. }
  5416. checkTypeInst = checkTypeInst->GetImplBaseType();
  5417. }
  5418. if (mSystem->mPtrSize == 8)
  5419. {
  5420. int intPtrCount = (dynCastDataElems + 1) / 2;
  5421. vDataOfs += intPtrCount;
  5422. uint64* intPtrData = (uint64*)&dynCastData[0];
  5423. for (int i = 0; i < intPtrCount; i++)
  5424. {
  5425. uint64 val = intPtrData[i];
  5426. if (val == 0)
  5427. {
  5428. vData.push_back(voidPtrNull);
  5429. }
  5430. else
  5431. {
  5432. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5433. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5434. }
  5435. }
  5436. }
  5437. else
  5438. {
  5439. int intPtrCount = dynCastDataElems;
  5440. vDataOfs += intPtrCount;
  5441. uint32* intPtrData = (uint32*)&dynCastData[0];
  5442. for (int i = 0; i < intPtrCount; i++)
  5443. {
  5444. uint32 val = intPtrData[i];
  5445. if (val == 0)
  5446. {
  5447. vData.push_back(voidPtrNull);
  5448. }
  5449. else
  5450. {
  5451. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  5452. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5453. }
  5454. }
  5455. }
  5456. }
  5457. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  5458. vData.push_back(voidPtrNull);
  5459. struct _InterfaceMatchEntry
  5460. {
  5461. BfTypeInterfaceEntry* mEntry;
  5462. BfTypeInstance* mEntrySource;
  5463. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  5464. };
  5465. int highestIFaceVirtIdx = 0;
  5466. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  5467. auto checkTypeInst = typeInstance;
  5468. bool forceInterfaceSet = false;
  5469. while (checkTypeInst != NULL)
  5470. {
  5471. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5472. {
  5473. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  5474. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject)))
  5475. continue;
  5476. _InterfaceMatchEntry* matchEntry = NULL;
  5477. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  5478. {
  5479. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  5480. if (compareCheckTypeInst->IsBoxed())
  5481. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  5482. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  5483. if (compareEntrySource->IsBoxed())
  5484. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  5485. auto prevEntry = matchEntry->mEntry;
  5486. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  5487. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  5488. if ((!isBetter) && (!isWorse))
  5489. {
  5490. // Unboxed comparison to Object fix
  5491. if (compareCheckTypeInst == mContext->mBfObjectType)
  5492. isWorse = true;
  5493. else if (compareEntrySource == mContext->mBfObjectType)
  5494. isBetter = true;
  5495. }
  5496. if (forceInterfaceSet)
  5497. {
  5498. isBetter = true;
  5499. isWorse = false;
  5500. }
  5501. if (isBetter == isWorse)
  5502. CompareDeclTypes(checkTypeInst, interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  5503. if (isBetter == isWorse)
  5504. {
  5505. if (matchEntry->mAmbiguousEntries.empty())
  5506. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  5507. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  5508. continue;
  5509. }
  5510. else if (isBetter)
  5511. {
  5512. matchEntry->mEntry = &interfaceEntry;
  5513. matchEntry->mEntrySource = checkTypeInst;
  5514. matchEntry->mAmbiguousEntries.Clear();
  5515. }
  5516. else
  5517. continue;
  5518. }
  5519. else
  5520. {
  5521. _InterfaceMatchEntry matchEntry;
  5522. matchEntry.mEntry = &interfaceEntry;
  5523. matchEntry.mEntrySource = checkTypeInst;
  5524. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  5525. }
  5526. }
  5527. checkTypeInst = checkTypeInst->GetImplBaseType();
  5528. }
  5529. for (auto interfacePair : interfaceMap)
  5530. {
  5531. auto& interfaceMatchEntry = interfacePair.mValue;
  5532. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  5533. {
  5534. auto error = Fail(StrFormat("Type '%s' has an ambiguous declaration for interface '%s'", TypeToString(typeInstance).c_str(), TypeToString(interfaceMatchEntry.mEntry->mInterfaceType).c_str()), interfaceMatchEntry.mEntry->mDeclaringType->GetRefNode());
  5535. if (error != NULL)
  5536. {
  5537. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  5538. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  5539. }
  5540. }
  5541. }
  5542. if ((!mIsComptimeModule) && (!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  5543. {
  5544. int startTabIdx = (int)vData.size();
  5545. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  5546. BfTypeInstance* checkTypeInst = typeInstance;
  5547. while (checkTypeInst != NULL)
  5548. {
  5549. origVirtTypeStack.push_back(checkTypeInst);
  5550. checkTypeInst = checkTypeInst->GetImplBaseType();
  5551. }
  5552. Array<BfVirtualMethodEntry> origVTable;
  5553. int origVirtIdx = 0;
  5554. if (typeInstance->mTypeDef->mIsCombinedPartial)
  5555. {
  5556. HashSet<String> reslotNames;
  5557. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5558. {
  5559. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5560. if (entry.mDeclaringMethod.mMethodNum == -1)
  5561. continue;
  5562. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5563. if ((methodInstance == NULL) ||
  5564. ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))))
  5565. {
  5566. if (origVTable.empty())
  5567. origVTable = typeInstance->mVirtualMethodTable;
  5568. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  5569. if ((mIsComptimeModule) || (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject)))
  5570. {
  5571. // Prepare to reslot...
  5572. entry.mImplementingMethod = entry.mDeclaringMethod;
  5573. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  5574. }
  5575. else
  5576. {
  5577. // Decl isn't accessible, null out entry
  5578. entry.mImplementingMethod = BfMethodRef();
  5579. }
  5580. }
  5581. }
  5582. if (!reslotNames.IsEmpty())
  5583. {
  5584. BfAmbiguityContext ambiguityContext;
  5585. ambiguityContext.mTypeInstance = typeInstance;
  5586. ambiguityContext.mModule = this;
  5587. ambiguityContext.mIsProjectSpecific = true;
  5588. ambiguityContext.mIsReslotting = true;
  5589. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5590. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  5591. {
  5592. auto methodInstance = methodGroup.mDefault;
  5593. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  5594. continue;
  5595. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  5596. continue;
  5597. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  5598. continue;
  5599. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  5600. continue;
  5601. SlotVirtualMethod(methodInstance, &ambiguityContext);
  5602. }
  5603. ambiguityContext.Finish();
  5604. }
  5605. }
  5606. bool isInExts = false;
  5607. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5608. {
  5609. BfIRValue vValue = voidPtrNull;
  5610. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5611. BfModuleMethodInstance moduleMethodInst;
  5612. if (entry.mDeclaringMethod.mMethodNum == -1)
  5613. {
  5614. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  5615. isInExts = true;
  5616. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  5617. if (vExt)
  5618. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  5619. }
  5620. else
  5621. {
  5622. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  5623. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  5624. {
  5625. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  5626. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  5627. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5628. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5629. {
  5630. BF_ASSERT((mIsComptimeModule) || typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  5631. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5632. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5633. vValue = funcPtr;
  5634. }
  5635. }
  5636. }
  5637. while (origVirtTypeStack.size() != 0)
  5638. {
  5639. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  5640. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  5641. {
  5642. // Moved past current base vtable size
  5643. origVirtTypeStack.pop_back();
  5644. continue;
  5645. }
  5646. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  5647. {
  5648. // We are within the original vtable size
  5649. int idx = startTabIdx + origVirtIdx;
  5650. origVirtIdx++;
  5651. vData.push_back(vValue);
  5652. }
  5653. else
  5654. {
  5655. // This is a new entry, it only gets added to the ext
  5656. BF_ASSERT(isInExts);
  5657. }
  5658. break;
  5659. }
  5660. }
  5661. if (!origVTable.empty())
  5662. typeInstance->mVirtualMethodTable = origVTable;
  5663. }
  5664. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  5665. if (typeInstance->mHotTypeData != NULL)
  5666. {
  5667. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  5668. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  5669. }
  5670. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  5671. int iFaceMethodStartIdx = (int)vData.size();
  5672. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  5673. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  5674. vData[i] = voidPtrNull;
  5675. if (expectNumElements != 0)
  5676. BF_ASSERT(expectNumElements == vData.size());
  5677. //BF_ASSERT(vData.size() == expectNumElements);
  5678. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  5679. // ifaceMethodExtData.Add(voidPtrNull);
  5680. int ifaceEntryIdx = iFaceMethodStartIdx;
  5681. for (auto& interfacePair : interfaceMap)
  5682. {
  5683. auto interfaceEntry = interfacePair.mValue.mEntry;
  5684. if (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  5685. {
  5686. BF_ASSERT(mIsComptimeModule);
  5687. break;
  5688. }
  5689. bool makeEmpty = false;
  5690. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject)))
  5691. makeEmpty = true;
  5692. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5693. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  5694. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5695. {
  5696. BfIRValue pushValue;
  5697. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5698. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5699. continue;
  5700. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5701. continue;
  5702. if (makeEmpty)
  5703. {
  5704. pushValue = voidPtrNull;
  5705. }
  5706. else
  5707. {
  5708. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5709. auto methodInstance = (BfMethodInstance*)methodRef;
  5710. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5711. {
  5712. BF_ASSERT(methodInstance->mIsReified);
  5713. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5714. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5715. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5716. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5717. pushValue = funcPtr;
  5718. }
  5719. else
  5720. {
  5721. pushValue = voidPtrNull;
  5722. }
  5723. }
  5724. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5725. if (idx < ifaceMethodExtStart)
  5726. {
  5727. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  5728. vData[iFaceMethodStartIdx + idx] = pushValue;
  5729. }
  5730. else
  5731. {
  5732. BF_ASSERT(useExt);
  5733. int extIdx = idx - ifaceMethodExtStart;
  5734. while (extIdx >= ifaceMethodExtData.size())
  5735. ifaceMethodExtData.Add(voidPtrNull);
  5736. ifaceMethodExtData[extIdx] = pushValue;
  5737. }
  5738. }
  5739. }
  5740. if (typeInstance->IsBoxed())
  5741. {
  5742. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  5743. if (boxedType->IsBoxedStructPtr())
  5744. {
  5745. // Force override of GetHashCode so we use the pointer address as the hash code
  5746. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  5747. // Force override of GetHashCode so we use the pointer address as the hash code
  5748. for (auto& checkIFace : checkTypeInst->mInterfaces)
  5749. {
  5750. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5751. {
  5752. BfIRValue pushValue;
  5753. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5754. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5755. continue;
  5756. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5757. continue;
  5758. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5759. auto methodInstance = (BfMethodInstance*)methodRef;
  5760. BF_ASSERT(methodInstance->mIsReified);
  5761. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5762. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5763. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5764. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5765. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5766. vData[iFaceMethodStartIdx + idx] = funcPtr;
  5767. }
  5768. }
  5769. }
  5770. }
  5771. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic) && (!mIsComptimeModule))
  5772. {
  5773. BfIRValue ifaceMethodExtVar;
  5774. if ((!ifaceMethodExtData.IsEmpty()) && (!mIsComptimeModule))
  5775. {
  5776. StringT<512> classVDataName;
  5777. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  5778. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  5779. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  5780. BfIRLinkageType_External, BfIRValue(), classVDataName);
  5781. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  5782. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, ifaceMethodExtData);
  5783. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  5784. }
  5785. for (auto& ifaceInstPair : interfaceMap)
  5786. {
  5787. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  5788. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  5789. if (slotNum >= 0)
  5790. {
  5791. BfIRValue vtablePtr;
  5792. int idx = interfaceEntry->mStartVirtualIdx;
  5793. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5794. if ((endVirtualIdx > ifaceMethodExtStart) && (ifaceMethodExtVar))
  5795. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  5796. else
  5797. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  5798. int slotVirtIdx = slotNum + vDataOfs;
  5799. if (vData[slotVirtIdx] == voidPtrNull)
  5800. {
  5801. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  5802. }
  5803. else
  5804. {
  5805. if (mCompiler->IsHotCompile())
  5806. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  5807. else
  5808. Fail("Interface slot collision error", typeDef->GetRefNode());
  5809. }
  5810. }
  5811. }
  5812. }
  5813. }
  5814. BfIRValue typeNameConst;
  5815. BfIRValue namespaceConst;
  5816. if (needsTypeNames)
  5817. {
  5818. typeNameConst = GetStringObjectValue(typeDef->mName->mString, !mIsComptimeModule);
  5819. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), !mIsComptimeModule);
  5820. }
  5821. else
  5822. {
  5823. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  5824. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5825. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5826. }
  5827. int baseTypeId = 0;
  5828. if (typeInstance->mBaseType != NULL)
  5829. {
  5830. baseTypeId = typeInstance->mBaseType->mTypeId;
  5831. }
  5832. BfTypeOptions* typeOptions = NULL;
  5833. if (typeInstance->mTypeOptionsIdx >= 0)
  5834. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5835. SizedArray<BfIRValue, 16> customAttrs;
  5836. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  5837. BfIRValue castedClassVData;
  5838. if (classVDataVar)
  5839. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  5840. else
  5841. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  5842. bool freflectIncludeTypeData = false;
  5843. bool reflectIncludeAllFields = false;
  5844. bool reflectIncludeAllMethods = false;
  5845. if (TypeIsSubTypeOf(typeInstance, attributeType))
  5846. {
  5847. reflectIncludeAllFields = true;
  5848. reflectIncludeAllMethods = true;
  5849. }
  5850. BfReflectKind reflectKind = BfReflectKind_Type;
  5851. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  5852. {
  5853. BfReflectKind reflectKind = BfReflectKind_None;
  5854. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  5855. if (customAttrs != NULL)
  5856. {
  5857. for (auto& attr : customAttrs->mAttributes)
  5858. {
  5859. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  5860. }
  5861. delete customAttrs;
  5862. }
  5863. return reflectKind;
  5864. };
  5865. reflectKind = GetReflectKind(reflectKind, typeInstance);
  5866. // Fields
  5867. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  5868. BfIRValue emptyValueType = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  5869. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  5870. {
  5871. if (customAttributes == NULL)
  5872. return -1;
  5873. Array<BfCustomAttribute*> reflectAttributes;
  5874. for (auto& attr : customAttributes->mAttributes)
  5875. {
  5876. bool wantAttribute = false;
  5877. if (attr.mType->mCustomAttributes != NULL)
  5878. {
  5879. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  5880. if (usageAttribute != NULL)
  5881. {
  5882. // Check for Flags arg
  5883. if (usageAttribute->mCtorArgs.size() < 2)
  5884. continue;
  5885. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  5886. if (constant == NULL)
  5887. continue;
  5888. if (constant->mTypeCode == BfTypeCode_Boolean)
  5889. continue;
  5890. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  5891. wantAttribute = true;
  5892. }
  5893. }
  5894. if ((wantAttribute) && (attr.mType->mIsReified))
  5895. {
  5896. reflectAttributes.Add(&attr);
  5897. }
  5898. }
  5899. if (reflectAttributes.size() == 0)
  5900. return -1;
  5901. #define PUSH_INT8(val) data.push_back((uint8)val)
  5902. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  5903. #define PUSH_INT32(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); data.push_back((val >> 16) & 0xFF); data.push_back((val >> 24) & 0xFF); }
  5904. SizedArray<uint8, 16> data;
  5905. int customAttrIdx = (int)customAttrs.size();
  5906. data.push_back((uint8)reflectAttributes.size());
  5907. for (auto attr : reflectAttributes)
  5908. {
  5909. // Size prefix
  5910. int sizeIdx = (int)data.size();
  5911. PUSH_INT16(0); // mSize
  5912. PUSH_INT32(attr->mType->mTypeId); // mType
  5913. int ctorIdx = -1;
  5914. int ctorCount = 0;
  5915. attr->mType->mTypeDef->PopulateMemberSets();
  5916. BfMemberSetEntry* entry;
  5917. if (attr->mType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  5918. {
  5919. BfMethodDef* nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5920. while (nextMethodDef != NULL)
  5921. {
  5922. if (nextMethodDef == attr->mCtor)
  5923. ctorIdx = ctorCount;
  5924. nextMethodDef = nextMethodDef->mNextWithSameName;
  5925. ctorCount++;
  5926. }
  5927. }
  5928. BF_ASSERT(ctorIdx != -1);
  5929. if (ctorIdx != -1)
  5930. ctorIdx = (ctorCount - 1) - ctorIdx;
  5931. PUSH_INT16(ctorIdx);
  5932. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  5933. int argIdx = 0;
  5934. for (auto arg : attr->mCtorArgs)
  5935. {
  5936. auto argType = ctorMethodInstance->GetParamType(argIdx);
  5937. EncodeAttributeData(typeInstance, argType, arg, data, usedStringIdMap);
  5938. argIdx++;
  5939. }
  5940. int size = (int)data.size() - sizeIdx;
  5941. *((uint16*)&data[sizeIdx]) = size;
  5942. }
  5943. #undef PUSH_INT8
  5944. #undef PUSH_INT16
  5945. #undef PUSH_INT32
  5946. SizedArray<BfIRValue, 16> dataValues;
  5947. for (uint8 val : data)
  5948. dataValues.push_back(GetConstValue8(val));
  5949. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  5950. auto customAttrConst = mBfIRBuilder->CreateConstAgg_Value(dataArrayType, dataValues);
  5951. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  5952. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  5953. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  5954. customAttrs.push_back(customAttrArrayPtr);
  5955. return customAttrIdx;
  5956. };
  5957. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  5958. SizedArray<int, 16> reflectFieldIndices;
  5959. for (int pass = 0; pass < 2; pass++)
  5960. {
  5961. bool skippedField = false;
  5962. reflectFieldIndices.clear();
  5963. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  5964. {
  5965. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5966. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5967. if (fieldDef == NULL)
  5968. continue;
  5969. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  5970. bool includeField = reflectIncludeAllFields;
  5971. if (fieldInstance->mCustomAttributes != NULL)
  5972. {
  5973. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  5974. {
  5975. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  5976. {
  5977. includeField = true;
  5978. }
  5979. else
  5980. {
  5981. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  5982. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  5983. }
  5984. }
  5985. }
  5986. if ((fieldReflectKind & BfReflectKind_User) != 0)
  5987. includeField = true;
  5988. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  5989. includeField = true;
  5990. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  5991. includeField = true;
  5992. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  5993. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  5994. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  5995. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  5996. includeField |= forceReflectFields;
  5997. if (!includeField)
  5998. {
  5999. skippedField = true;
  6000. continue;
  6001. }
  6002. reflectFieldIndices.Add(fieldIdx);
  6003. }
  6004. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  6005. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  6006. // possible because we write out a SplatData structure containing just TypeIds in that case
  6007. if (pass == 0)
  6008. {
  6009. if (!typeInstance->IsSplattable())
  6010. break;
  6011. if (!skippedField)
  6012. break;
  6013. if (reflectFieldIndices.size() == 0)
  6014. break;
  6015. }
  6016. }
  6017. SizedArray<BfIRValue, 16> fieldTypes;
  6018. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  6019. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  6020. {
  6021. BfType* payloadType = typeInstance->GetUnionInnerType();
  6022. if (!payloadType->IsValuelessType())
  6023. {
  6024. BfIRValue payloadNameConst = GetStringObjectValue("$payload", !mIsComptimeModule);
  6025. SizedArray<BfIRValue, 8> payloadFieldVals;
  6026. if (is32Bit)
  6027. {
  6028. payloadFieldVals =
  6029. {
  6030. emptyValueType,
  6031. payloadNameConst, // mName
  6032. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6033. GetConstValue(0, intPtrType), // mData
  6034. GetConstValue(0, intPtrType), // mDataHi
  6035. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6036. GetConstValue(-1, intType), // mCustomAttributesIdx
  6037. };
  6038. }
  6039. else
  6040. {
  6041. payloadFieldVals =
  6042. {
  6043. emptyValueType,
  6044. payloadNameConst, // mName
  6045. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6046. GetConstValue(0, intPtrType), // mData
  6047. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6048. GetConstValue(-1, intType), // mCustomAttributesIdx
  6049. };
  6050. }
  6051. FixConstValueParams(reflectFieldDataType->ToTypeInstance(), payloadFieldVals);
  6052. auto payloadFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  6053. fieldTypes.push_back(payloadFieldData);
  6054. }
  6055. BfType* dscrType = typeInstance->GetDiscriminatorType();
  6056. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", !mIsComptimeModule);
  6057. SizedArray<BfIRValue, 8> dscrFieldVals;
  6058. if (is32Bit)
  6059. {
  6060. dscrFieldVals =
  6061. {
  6062. emptyValueType,
  6063. dscrNameConst, // mName
  6064. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6065. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6066. GetConstValue(0, intPtrType), // mDataHi
  6067. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6068. GetConstValue(-1, intType), // mCustomAttributesIdx
  6069. };
  6070. }
  6071. else
  6072. {
  6073. dscrFieldVals =
  6074. {
  6075. emptyValueType,
  6076. dscrNameConst, // mName
  6077. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6078. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6079. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6080. GetConstValue(-1, intType), // mCustomAttributesIdx
  6081. };
  6082. }
  6083. auto dscrFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  6084. fieldTypes.push_back(dscrFieldData);
  6085. }
  6086. for (auto fieldIdx : reflectFieldIndices)
  6087. {
  6088. if (!needsTypeData)
  6089. break;
  6090. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6091. fieldTypes.push_back(CreateFieldData(fieldInstance, _HandleCustomAttrs(fieldInstance->mCustomAttributes)));
  6092. }
  6093. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  6094. BfIRValue fieldDataPtr;
  6095. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  6096. if (fieldTypes.size() == 0)
  6097. {
  6098. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  6099. {
  6100. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  6101. SizedArray<BfIRValue, 3> splatTypes;
  6102. SizedArray<BfIRValue, 3> splatOffsets;
  6103. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  6104. {
  6105. auto checkTypeInstance = checkType->ToTypeInstance();
  6106. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  6107. PopulateType(checkTypeInstance);
  6108. if (checkType->IsStruct())
  6109. {
  6110. int dataEnd = offset;
  6111. if (checkTypeInstance->mBaseType != NULL)
  6112. _CheckSplat(checkTypeInstance->mBaseType, offset);
  6113. if (checkTypeInstance->mIsUnion)
  6114. {
  6115. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  6116. _CheckSplat(unionInnerType, offset);
  6117. }
  6118. else
  6119. {
  6120. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  6121. {
  6122. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  6123. if (fieldInstance->mDataIdx >= 0)
  6124. {
  6125. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  6126. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  6127. }
  6128. }
  6129. }
  6130. if (checkTypeInstance->IsEnum())
  6131. {
  6132. // Add discriminator
  6133. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  6134. if (checkTypeInstance->mPacking > 0)
  6135. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  6136. _CheckSplat(dscrType, dataEnd);
  6137. }
  6138. }
  6139. else if (checkType->IsMethodRef())
  6140. {
  6141. // auto methodRefType = (BfMethodRefType*)checkType;
  6142. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6143. // {
  6144. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6145. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  6146. // else
  6147. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  6148. // }
  6149. }
  6150. else if (!checkType->IsValuelessType())
  6151. {
  6152. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  6153. splatOffsets.Add(GetConstValue(offset, intType));
  6154. }
  6155. };
  6156. _CheckSplat(type, 0);
  6157. while (splatTypes.size() < 3)
  6158. {
  6159. splatTypes.Add(GetConstValue(0, typeIdType));
  6160. splatOffsets.Add(GetConstValue(0, intType));
  6161. }
  6162. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  6163. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  6164. SizedArray<BfIRValue, 8> splatVals =
  6165. {
  6166. emptyValueType,
  6167. splatTypesConst,
  6168. splatOffsetsConst
  6169. };
  6170. auto fieldSplatData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  6171. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  6172. fieldSplatData, typeDataName + ".splats");
  6173. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6174. }
  6175. else
  6176. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  6177. }
  6178. else
  6179. {
  6180. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  6181. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstAgg_Value(fieldDataConstType, fieldTypes);
  6182. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  6183. fieldDataConst, "fields." + typeDataName);
  6184. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6185. }
  6186. /// Methods
  6187. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  6188. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  6189. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  6190. struct _SortedMethodInfo
  6191. {
  6192. BfMethodDef* mMethodDef;
  6193. BfMethodCustomAttributes* mMethodCustomAttributes;
  6194. };
  6195. Array<_SortedMethodInfo> sortedMethodList;
  6196. SizedArray<BfIRValue, 16> methodTypes;
  6197. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  6198. {
  6199. if (!needsTypeData)
  6200. break;
  6201. // Disable const method reflection info for now
  6202. if (mIsComptimeModule)
  6203. break;
  6204. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6205. if (!methodInstanceGroup->IsImplemented())
  6206. continue;
  6207. auto methodDef = typeDef->mMethods[methodIdx];
  6208. if (methodDef->mIsNoReflect)
  6209. continue;
  6210. if (methodDef->mHasComptime)
  6211. continue;
  6212. auto defaultMethod = methodInstanceGroup->mDefault;
  6213. if (defaultMethod == NULL)
  6214. continue;
  6215. if (defaultMethod->mIsUnspecialized)
  6216. continue;
  6217. if (!defaultMethod->mIsReified)
  6218. continue;
  6219. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  6220. continue;
  6221. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  6222. continue;
  6223. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6224. bool includeMethod = reflectIncludeAllMethods;
  6225. BfMethodCustomAttributes* methodCustomAttributes = NULL;
  6226. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  6227. {
  6228. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes;
  6229. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  6230. {
  6231. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6232. {
  6233. includeMethod = true;
  6234. }
  6235. else
  6236. {
  6237. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6238. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  6239. }
  6240. }
  6241. }
  6242. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject)))
  6243. continue;
  6244. //
  6245. {
  6246. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  6247. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  6248. {
  6249. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  6250. {
  6251. if (paramDecl->mAttributes != NULL)
  6252. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  6253. }
  6254. }
  6255. }
  6256. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  6257. includeMethod = true;
  6258. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  6259. includeMethod = true;
  6260. if ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend))
  6261. {
  6262. if ((methodReflectKind & BfReflectKind_Constructors) != 0)
  6263. includeMethod = true;
  6264. if ((methodDef->IsDefaultCtor()) && ((methodReflectKind & BfReflectKind_DefaultConstructor) != 0))
  6265. includeMethod = true;
  6266. }
  6267. if ((!includeMethod) && (typeOptions != NULL))
  6268. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  6269. if (!includeMethod)
  6270. continue;
  6271. sortedMethodList.Add({ methodDef, methodCustomAttributes });
  6272. }
  6273. auto _GetMethodKind = [](BfMethodDef* methodDef)
  6274. {
  6275. if (methodDef->mMethodType == BfMethodType_Ctor)
  6276. return 0;
  6277. return 1;
  6278. };
  6279. std::sort(sortedMethodList.begin(), sortedMethodList.end(), [_GetMethodKind](const _SortedMethodInfo& lhs, const _SortedMethodInfo& rhs)
  6280. {
  6281. int lhsKind = _GetMethodKind(lhs.mMethodDef);
  6282. int rhsKind = _GetMethodKind(rhs.mMethodDef);
  6283. if (lhsKind != rhsKind)
  6284. return lhsKind < rhsKind;
  6285. if (lhs.mMethodDef->mName != rhs.mMethodDef->mName)
  6286. return lhs.mMethodDef->mName < rhs.mMethodDef->mName;
  6287. return lhs.mMethodDef->mIdx < rhs.mMethodDef->mIdx;
  6288. });
  6289. for (auto& methodInfo : sortedMethodList)
  6290. {
  6291. auto methodDef = methodInfo.mMethodDef;
  6292. int methodIdx = methodDef->mIdx;
  6293. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6294. auto defaultMethod = methodInstanceGroup->mDefault;
  6295. BfModuleMethodInstance moduleMethodInstance;
  6296. BfIRValue funcVal = voidPtrNull;
  6297. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  6298. (!typeInstance->IsUnspecializedType()) &&
  6299. (methodDef->mMethodType != BfMethodType_Ignore) &&
  6300. (methodDef->mMethodType != BfMethodType_Mixin) &&
  6301. (!methodDef->mIsAbstract) &&
  6302. (methodDef->mGenericParams.size() == 0))
  6303. {
  6304. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6305. if (moduleMethodInstance.mFunc)
  6306. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6307. }
  6308. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, !mIsComptimeModule);
  6309. BfMethodFlags methodFlags = defaultMethod->GetMethodFlags();
  6310. int customAttrIdx = -1;
  6311. int returnCustomAttrIdx = -1;
  6312. if (methodInfo.mMethodCustomAttributes != NULL)
  6313. {
  6314. customAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mCustomAttributes);
  6315. returnCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mReturnCustomAttributes);
  6316. }
  6317. enum ParamFlags
  6318. {
  6319. ParamFlag_None = 0,
  6320. ParamFlag_Splat = 1,
  6321. ParamFlag_Implicit = 2,
  6322. ParamFlag_AppendIdx = 4,
  6323. ParamFlag_Params = 8
  6324. };
  6325. SizedArray<BfIRValue, 8> paramVals;
  6326. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  6327. {
  6328. String paramName = defaultMethod->GetParamName(paramIdx);
  6329. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  6330. ParamFlags paramFlags = ParamFlag_None;
  6331. if (defaultMethod->GetParamIsSplat(paramIdx))
  6332. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  6333. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  6334. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Implicit | ParamFlag_AppendIdx);
  6335. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_Params)
  6336. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Params);
  6337. BfIRValue paramNameConst = GetStringObjectValue(paramName, !mIsComptimeModule);
  6338. int paramCustomAttrIdx = -1;
  6339. if ((methodInfo.mMethodCustomAttributes != NULL) && (paramIdx < (int)methodInfo.mMethodCustomAttributes->mParamCustomAttributes.mSize))
  6340. paramCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mParamCustomAttributes[paramIdx]);
  6341. SizedArray<BfIRValue, 8> paramDataVals =
  6342. {
  6343. emptyValueType,
  6344. paramNameConst,
  6345. GetConstValue(paramType->mTypeId, typeIdType),
  6346. GetConstValue((int32)paramFlags, shortType),
  6347. GetConstValue(-1, intType), // defaultIdx
  6348. GetConstValue(paramCustomAttrIdx, intType) // customAttrIdx
  6349. };
  6350. auto paramData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  6351. paramVals.Add(paramData);
  6352. }
  6353. BfIRValue paramsVal;
  6354. if (paramVals.size() > 0)
  6355. {
  6356. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  6357. BfIRValue paramDataConst = mBfIRBuilder->CreateConstAgg_Value(paramDataArrayType, paramVals);
  6358. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  6359. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  6360. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  6361. }
  6362. else
  6363. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  6364. int vDataVal = -1;
  6365. if (defaultMethod->mVirtualTableIdx != -1)
  6366. {
  6367. int vDataIdx = -1;
  6368. if (type->IsInterface())
  6369. {
  6370. vDataIdx = defaultMethod->mVirtualTableIdx;
  6371. }
  6372. else
  6373. {
  6374. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  6375. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  6376. {
  6377. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  6378. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6379. if (extMethodIdx >= 0)
  6380. {
  6381. // Extension?
  6382. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6383. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  6384. }
  6385. else
  6386. {
  6387. // Map this new virtual index back to the original index
  6388. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  6389. }
  6390. }
  6391. else
  6392. {
  6393. vDataIdx += defaultMethod->mVirtualTableIdx;
  6394. }
  6395. }
  6396. if (vDataVal == -1)
  6397. vDataVal = vDataIdx * mSystem->mPtrSize;
  6398. }
  6399. SizedArray<BfIRValue, 8> methodDataVals =
  6400. {
  6401. emptyValueType,
  6402. methodNameConst, // mName
  6403. funcVal, // mFuncPtr
  6404. paramsVal,
  6405. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  6406. GetConstValue((int)paramVals.size(), shortType),
  6407. GetConstValue(methodFlags, shortType),
  6408. GetConstValue(methodIdx, intType),
  6409. GetConstValue(vDataVal, intType),
  6410. GetConstValue(customAttrIdx, intType),
  6411. GetConstValue(returnCustomAttrIdx, intType),
  6412. };
  6413. auto methodData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  6414. methodTypes.push_back(methodData);
  6415. }
  6416. BfIRValue methodDataPtr;
  6417. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  6418. if (methodTypes.size() == 0)
  6419. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  6420. else
  6421. {
  6422. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  6423. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methodTypes);
  6424. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6425. methodDataConst, "methods." + typeDataName);
  6426. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  6427. }
  6428. /////
  6429. int interfaceCount = 0;
  6430. BfIRValue interfaceDataPtr;
  6431. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  6432. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  6433. Array<bool> wantsIfaceMethod;
  6434. bool wantsIfaceMethods = false;
  6435. if (typeInstance->mInterfaces.IsEmpty())
  6436. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  6437. else
  6438. {
  6439. SizedArray<BfIRValue, 16> interfaces;
  6440. for (auto& interface : typeInstance->mInterfaces)
  6441. {
  6442. SizedArray<BfIRValue, 8> interfaceDataVals =
  6443. {
  6444. emptyValueType,
  6445. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  6446. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  6447. GetConstValue(interface.mStartVirtualIdx, intType),
  6448. };
  6449. auto interfaceData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  6450. interfaces.push_back(interfaceData);
  6451. if (!mIsComptimeModule)
  6452. {
  6453. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6454. {
  6455. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  6456. if (ifaceMethodGroup->mExplicitlyReflected)
  6457. {
  6458. wantsIfaceMethods = true;
  6459. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  6460. while (tableIdx >= wantsIfaceMethod.size())
  6461. wantsIfaceMethod.Add(false);
  6462. wantsIfaceMethod[tableIdx] = true;
  6463. }
  6464. }
  6465. }
  6466. }
  6467. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  6468. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstAgg_Value(interfaceDataArrayType, interfaces);
  6469. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  6470. interfaceDataConst, "interfaces." + typeDataName);
  6471. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  6472. interfaceCount = (int)interfaces.size();
  6473. }
  6474. BfIRValue interfaceMethodTable;
  6475. int ifaceMethodTableSize = 0;
  6476. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  6477. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  6478. {
  6479. SizedArray<BfIRValue, 16> methods;
  6480. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  6481. {
  6482. BfIRValue funcVal = voidPtrNull;
  6483. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  6484. {
  6485. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  6486. if (!methodEntry.mMethodRef.IsNull())
  6487. {
  6488. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  6489. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  6490. (!methodInstance->mMethodDef->mIsAbstract))
  6491. {
  6492. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  6493. if (moduleMethodInstance.mFunc)
  6494. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6495. }
  6496. }
  6497. }
  6498. methods.Add(funcVal);
  6499. }
  6500. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  6501. methods.pop_back();
  6502. if (!methods.IsEmpty())
  6503. {
  6504. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  6505. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methods);
  6506. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6507. methodDataConst, "imethods." + typeDataName);
  6508. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  6509. ifaceMethodTableSize = (int)methods.size();
  6510. }
  6511. }
  6512. if (!interfaceMethodTable)
  6513. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6514. /////
  6515. int underlyingType = 0;
  6516. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  6517. {
  6518. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  6519. }
  6520. int outerTypeId = 0;
  6521. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  6522. if (outerType != NULL)
  6523. {
  6524. outerTypeId = outerType->mTypeId;
  6525. }
  6526. //
  6527. BfIRValue customAttrDataPtr;
  6528. if (customAttrs.size() > 0)
  6529. {
  6530. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  6531. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstAgg_Value(customAttrsArrayType, customAttrs);
  6532. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  6533. customAttrsConst, "customAttrs." + typeDataName);
  6534. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  6535. }
  6536. else
  6537. {
  6538. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6539. }
  6540. SizedArray<BfIRValue, 32> typeDataVals =
  6541. {
  6542. typeData,
  6543. castedClassVData, // mTypeClassVData
  6544. typeNameConst, // mName
  6545. namespaceConst, // mNamespace
  6546. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  6547. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  6548. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  6549. GetConstValue(baseTypeId, typeIdType), // mBaseType
  6550. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  6551. GetConstValue(outerTypeId, typeIdType), // mOuterType
  6552. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  6553. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  6554. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  6555. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  6556. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  6557. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  6558. GetConstValue(0, shortType), // mPropertyDataCount
  6559. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  6560. interfaceDataPtr, // mInterfaceDataPtr
  6561. interfaceMethodTable, // mInterfaceMethodTable
  6562. methodDataPtr, // mMethodDataPtr
  6563. voidPtrNull, // mPropertyDataPtr
  6564. fieldDataPtr, // mFieldDataPtr
  6565. customAttrDataPtr, // mCustomAttrDataPtr
  6566. };
  6567. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  6568. FixConstValueParams(typeInstanceType->ToTypeInstance(), typeDataVals);
  6569. auto typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, typeDataVals);
  6570. if (!needsTypeData)
  6571. {
  6572. // No need for anything beyond typeInstanceData
  6573. }
  6574. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  6575. {
  6576. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6577. SizedArray<BfIRValue, 4> unspecializedData =
  6578. {
  6579. typeInstanceData,
  6580. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  6581. };
  6582. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  6583. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6584. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, unspecializedData);
  6585. }
  6586. else if (typeInstance->IsGenericTypeInstance())
  6587. {
  6588. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6589. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  6590. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef->GetDefinition());
  6591. SizedArray<BfIRValue, 4> resolvedTypes;
  6592. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  6593. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  6594. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  6595. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  6596. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  6597. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstAgg_Value(genericArrayType, resolvedTypes);
  6598. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  6599. resolvedTypesConst, "resolvedTypes." + typeDataName);
  6600. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  6601. SizedArray<BfIRValue, 3> specGenericData =
  6602. {
  6603. typeInstanceData,
  6604. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  6605. resovledTypesPtr, // mFieldDataPtr
  6606. };
  6607. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6608. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, specGenericData);
  6609. if (typeInstance->IsArray())
  6610. {
  6611. auto arrayType = (BfArrayType*)typeInstance;
  6612. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  6613. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  6614. SizedArray<BfIRValue, 4> arrayData =
  6615. {
  6616. typeInstanceData,
  6617. GetConstValue(elementType->mSize, intType), // mElementSize
  6618. GetConstValue(1, byteType), // mRank
  6619. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  6620. };
  6621. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  6622. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  6623. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, arrayData);
  6624. }
  6625. }
  6626. BfIRValue typeDataVar;
  6627. if (needsTypeData)
  6628. {
  6629. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  6630. BfIRLinkageType_External, typeInstanceData, typeDataName);
  6631. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  6632. if (mBfIRBuilder->DbgHasInfo())
  6633. {
  6634. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  6635. }
  6636. }
  6637. else
  6638. {
  6639. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  6640. }
  6641. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  6642. mTypeDataRefs[typeInstance] = typeDataVar;
  6643. if ((!mIsComptimeModule) && (classVDataVar))
  6644. {
  6645. BF_ASSERT(!classVDataName.IsEmpty());
  6646. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  6647. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  6648. auto classVDataConstData = mBfIRBuilder->CreateConstAgg_Value(classVDataConstDataType, vData);
  6649. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  6650. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6651. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  6652. else
  6653. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  6654. if (mBfIRBuilder->DbgHasInfo())
  6655. {
  6656. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6657. BfType* voidPtrType = CreatePointerType(voidType);
  6658. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6659. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  6660. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  6661. }
  6662. }
  6663. return typeDataVar;
  6664. }
  6665. BfIRValue BfModule::FixClassVData(BfIRValue value)
  6666. {
  6667. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  6668. return value;
  6669. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  6670. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  6671. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  6672. }
  6673. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  6674. {
  6675. // Note: this is not just for perf, it fixes a field var-type resolution issue
  6676. if (mBfIRBuilder->mIgnoreWrites)
  6677. return;
  6678. if (mIsComptimeModule)
  6679. return;
  6680. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  6681. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  6682. // When we access classes with static constructors FROM a static constructor,
  6683. // we call that other class's static constructor first. Recursion cannot occur, since
  6684. // we simply ignore subsequent attempts to re-enter the constructor
  6685. if (!typeInstance->mHasStaticInitMethod)
  6686. return;
  6687. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  6688. return;
  6689. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  6690. return;
  6691. auto checkTypeDef = typeInstance->mTypeDef;
  6692. checkTypeDef->PopulateMemberSets();
  6693. BfMethodDef* nextMethodDef = NULL;
  6694. BfMemberSetEntry* entry;
  6695. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  6696. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6697. while (nextMethodDef != NULL)
  6698. {
  6699. auto checkMethod = nextMethodDef;
  6700. nextMethodDef = nextMethodDef->mNextWithSameName;
  6701. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  6702. if (methodModule)
  6703. {
  6704. auto methodInstance = methodModule.mMethodInstance;
  6705. if ((methodInstance != NULL) &&
  6706. (methodInstance->mMethodDef->mIsStatic) &&
  6707. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  6708. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  6709. {
  6710. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  6711. break;
  6712. }
  6713. }
  6714. }
  6715. }
  6716. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  6717. {
  6718. auto methodOwner = methodInstance->GetOwner();
  6719. auto methodDef = methodInstance->mMethodDef;
  6720. auto methodDeclaration = methodDef->GetMethodDeclaration();
  6721. if (!methodDef->mIsExtern)
  6722. return BfIRFunction();
  6723. if (methodInstance->GetCustomAttributes() == NULL)
  6724. return BfIRFunction();
  6725. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  6726. {
  6727. String typeName = TypeToString(customAttribute.mType);
  6728. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  6729. {
  6730. methodInstance->mIsIntrinsic = true;
  6731. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  6732. String error;
  6733. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  6734. {
  6735. int stringId = constant->mInt32;
  6736. auto entry = mContext->mStringObjectIdMap[stringId];
  6737. String intrinName = entry.mString;
  6738. // if (intrinName.StartsWith(":"))
  6739. // {
  6740. // SizedArray<BfIRType, 2> paramTypes;
  6741. // for (auto& param : methodInstance->mParams)
  6742. // paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6743. // return mBfIRBuilder->GetIntrinsic(intrinName.Substring(1), mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6744. // }
  6745. // else
  6746. {
  6747. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  6748. if (intrinId != -1)
  6749. {
  6750. if (intrinId == BfIRIntrinsic_Malloc)
  6751. {
  6752. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6753. }
  6754. else if (intrinId == BfIRIntrinsic_Free)
  6755. {
  6756. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  6757. }
  6758. SizedArray<BfIRType, 2> paramTypes;
  6759. for (auto& param : methodInstance->mParams)
  6760. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6761. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6762. }
  6763. else if (reportFailure)
  6764. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  6765. }
  6766. }
  6767. else if (reportFailure)
  6768. error = "Intrinsic name must be a constant string";
  6769. if (reportFailure)
  6770. {
  6771. Fail(error, customAttribute.mRef);
  6772. }
  6773. }
  6774. }
  6775. return BfIRFunction();
  6776. }
  6777. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  6778. {
  6779. if (mBfIRBuilder->mIgnoreWrites)
  6780. return mBfIRBuilder->GetFakeFunction();
  6781. if (!mBuiltInFuncs[(int)funcTypeId])
  6782. {
  6783. SizedArray<BfIRType, 4> paramTypes;
  6784. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  6785. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6786. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  6787. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6788. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  6789. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  6790. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  6791. BfIRFunctionType funcType;
  6792. BfIRFunction func;
  6793. switch (funcTypeId)
  6794. {
  6795. case BfBuiltInFuncType_PrintF:
  6796. paramTypes.Add(nullPtrType);
  6797. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  6798. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  6799. break;
  6800. case BfBuiltInFuncType_Malloc:
  6801. {
  6802. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6803. {
  6804. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  6805. }
  6806. else
  6807. {
  6808. String funcName = mCompiler->mOptions.mMallocLinkName;
  6809. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  6810. funcName = "malloc";
  6811. func = mBfIRBuilder->GetFunction(funcName);
  6812. if (!func)
  6813. {
  6814. paramTypes.clear();
  6815. paramTypes.push_back(intType);
  6816. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  6817. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6818. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  6819. }
  6820. }
  6821. }
  6822. break;
  6823. case BfBuiltInFuncType_Free:
  6824. {
  6825. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6826. {
  6827. func = GetInternalMethod("Dbg_RawFree").mFunc;
  6828. }
  6829. else
  6830. {
  6831. String funcName = mCompiler->mOptions.mFreeLinkName;
  6832. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  6833. funcName = "free";
  6834. func = mBfIRBuilder->GetFunction(funcName);
  6835. if (!func)
  6836. {
  6837. paramTypes.clear();
  6838. paramTypes.push_back(nullPtrType);
  6839. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  6840. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6841. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  6842. }
  6843. }
  6844. }
  6845. break;
  6846. case BfBuiltInFuncType_LoadSharedLibraries:
  6847. paramTypes.clear();
  6848. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  6849. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  6850. break;
  6851. default: break;
  6852. }
  6853. mBuiltInFuncs[(int)funcTypeId] = func;
  6854. return func;
  6855. }
  6856. return mBuiltInFuncs[(int)funcTypeId];
  6857. }
  6858. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized, Array<BfTypeReference*>* deferredResolveTypes)
  6859. {
  6860. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  6861. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  6862. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  6863. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  6864. BfAutoComplete* bfAutocomplete = NULL;
  6865. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  6866. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  6867. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  6868. {
  6869. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  6870. {
  6871. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  6872. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  6873. {
  6874. String filter = nameNode->ToString();
  6875. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  6876. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  6877. if (nameIdx != 0)
  6878. {
  6879. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  6880. }
  6881. }
  6882. }
  6883. }
  6884. for (auto constraint : constraintDef->mConstraints)
  6885. {
  6886. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  6887. {
  6888. BfGenericOperatorConstraintInstance opConstraintInstance;
  6889. if (opConstraint->mLeftType != NULL)
  6890. {
  6891. if (bfAutocomplete != NULL)
  6892. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  6893. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces_All);
  6894. if (opConstraintInstance.mLeftType == NULL)
  6895. continue;
  6896. }
  6897. if (opConstraint->mRightType == NULL)
  6898. {
  6899. // We had a failure in parsing
  6900. continue;
  6901. }
  6902. if (opConstraint->mRightType != NULL)
  6903. {
  6904. if (bfAutocomplete != NULL)
  6905. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  6906. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces_All);
  6907. if (opConstraintInstance.mRightType == NULL)
  6908. continue;
  6909. }
  6910. if (opConstraint->mOpToken == NULL)
  6911. {
  6912. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  6913. continue;
  6914. }
  6915. if (opConstraint->mLeftType != NULL)
  6916. {
  6917. if (opConstraint->mRightType == NULL)
  6918. {
  6919. // Parse should have failed
  6920. continue;
  6921. }
  6922. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  6923. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  6924. {
  6925. Fail("Invalid binary operator", opConstraint->mOpToken);
  6926. continue;
  6927. }
  6928. }
  6929. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  6930. {
  6931. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  6932. }
  6933. else
  6934. {
  6935. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  6936. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  6937. {
  6938. Fail("Invalid unary operator", opConstraint->mOpToken);
  6939. continue;
  6940. }
  6941. }
  6942. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  6943. continue;
  6944. }
  6945. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  6946. if (bfAutocomplete != NULL)
  6947. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  6948. //TODO: Constraints may refer to other generic params (of either type or method)
  6949. // TO allow resolution, perhaps move this generic param initialization into GetMethodInstance (passing a genericPass bool)
  6950. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_AllowGenericMethodParamConstValue;
  6951. if (isUnspecialized)
  6952. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_DisallowComptime);
  6953. // We we have a deferredResolveTypes then we defer the generic validation, because we may have a case like
  6954. // `where T : Dictionay<TElem, int> and TElem : IHashable` and we don't want to throw the error on `T` before we build `TElem`
  6955. auto constraintType = ResolveTypeRef(constraintTypeRef, (deferredResolveTypes != NULL) ? BfPopulateType_Identity : BfPopulateType_Declaration, resolveFlags);
  6956. if (constraintType != NULL)
  6957. {
  6958. if (deferredResolveTypes != NULL)
  6959. {
  6960. PopulateType(constraintType, BfPopulateType_Declaration);
  6961. if (constraintType->IsUnspecializedTypeVariation())
  6962. deferredResolveTypes->Add(constraintTypeRef);
  6963. }
  6964. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6965. {
  6966. bool isValidTypeCode = false;
  6967. BfTypeCode typeCode = BfTypeCode_None;
  6968. if (constraintType->IsTypedPrimitive())
  6969. {
  6970. auto underlyingType = constraintType->GetUnderlyingType();
  6971. if (underlyingType->IsPrimitiveType())
  6972. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  6973. }
  6974. if (constraintType->IsPrimitiveType())
  6975. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  6976. if (constraintType->IsInstanceOf(mCompiler->mStringTypeDef))
  6977. isValidTypeCode = true;
  6978. switch (typeCode)
  6979. {
  6980. case BfTypeCode_StringId:
  6981. case BfTypeCode_Boolean:
  6982. case BfTypeCode_Int8:
  6983. case BfTypeCode_UInt8:
  6984. case BfTypeCode_Int16:
  6985. case BfTypeCode_UInt16:
  6986. case BfTypeCode_Int32:
  6987. case BfTypeCode_UInt32:
  6988. case BfTypeCode_Int64:
  6989. case BfTypeCode_UInt64:
  6990. case BfTypeCode_IntPtr:
  6991. case BfTypeCode_UIntPtr:
  6992. case BfTypeCode_IntUnknown:
  6993. case BfTypeCode_UIntUnknown:
  6994. case BfTypeCode_Float:
  6995. case BfTypeCode_Double:
  6996. case BfTypeCode_Char8:
  6997. case BfTypeCode_Char16:
  6998. case BfTypeCode_Char32:
  6999. isValidTypeCode = true;
  7000. break;
  7001. default: break;
  7002. }
  7003. if (isValidTypeCode)
  7004. {
  7005. genericParamInstance->mTypeConstraint = constraintType;
  7006. }
  7007. else
  7008. {
  7009. Fail("Const constraint must be a primitive type", constraintTypeRef);
  7010. }
  7011. }
  7012. else
  7013. {
  7014. bool checkEquality = false;
  7015. if (constraintType->IsVar())
  7016. {
  7017. // From a `comptype` generic undef resolution. Ignore.
  7018. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_ComptypeExpr);
  7019. genericParamInstance->mComptypeConstraint.Add(constraintTypeRef);
  7020. continue;
  7021. }
  7022. else if (constraintType->IsPrimitiveType())
  7023. {
  7024. if (isUnspecialized)
  7025. {
  7026. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  7027. continue;
  7028. }
  7029. checkEquality = true;
  7030. }
  7031. if (constraintType->IsArray())
  7032. {
  7033. if (isUnspecialized)
  7034. {
  7035. Fail("Array constraints are not allowed. If a constant-sized array was intended, an type parameterized by a const generic param can be used (ie: where T : int[T2] where T2 : const int)", constraintTypeRef);
  7036. continue;
  7037. }
  7038. checkEquality = true;
  7039. }
  7040. if (constraintType->IsGenericParam())
  7041. {
  7042. checkEquality = true;
  7043. }
  7044. else if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  7045. {
  7046. if (isUnspecialized)
  7047. {
  7048. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  7049. continue;
  7050. }
  7051. checkEquality = true;
  7052. }
  7053. if (checkEquality)
  7054. {
  7055. genericParamInstance->mTypeConstraint = constraintType;
  7056. }
  7057. else if (constraintType->IsInterface())
  7058. {
  7059. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  7060. }
  7061. else
  7062. {
  7063. auto constraintTypeInst = constraintType->ToTypeInstance();
  7064. if (genericParamInstance->mTypeConstraint != NULL)
  7065. {
  7066. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  7067. {
  7068. // Allow more specific type
  7069. genericParamInstance->mTypeConstraint = constraintTypeInst;
  7070. }
  7071. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  7072. {
  7073. // Silently ignore less-specific type
  7074. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  7075. {
  7076. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  7077. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Class);
  7078. }
  7079. }
  7080. else
  7081. {
  7082. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  7083. return;
  7084. }
  7085. }
  7086. else
  7087. genericParamInstance->mTypeConstraint = constraintType;
  7088. }
  7089. }
  7090. }
  7091. }
  7092. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  7093. (genericParamInstance->mTypeConstraint == NULL))
  7094. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  7095. }
  7096. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  7097. {
  7098. if (genericParamSource.mMethodInstance != NULL)
  7099. {
  7100. //auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  7101. //SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  7102. return MethodToString(genericParamSource.mMethodInstance);
  7103. }
  7104. else
  7105. {
  7106. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  7107. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  7108. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  7109. return TypeToString(typeInst);
  7110. }
  7111. }
  7112. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  7113. {
  7114. Array<String> methodParamNameOverrides;
  7115. auto _TypeToString = [&](BfType* type)
  7116. {
  7117. if (genericParamSource.mMethodInstance != NULL)
  7118. {
  7119. if (methodParamNameOverrides.IsEmpty())
  7120. {
  7121. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  7122. methodParamNameOverrides.Add(genericParam->mName);
  7123. }
  7124. return TypeToString(type, &methodParamNameOverrides);
  7125. }
  7126. return TypeToString(type);
  7127. };
  7128. bool ignoreErrors = (errorOut == NULL) ||
  7129. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  7130. BfType* origCheckArgType = checkArgType;
  7131. if (origCheckArgType->IsRef())
  7132. origCheckArgType = origCheckArgType->GetUnderlyingType();
  7133. bool argIsReferenceType = false;
  7134. int checkGenericParamFlags = 0;
  7135. if (checkArgType->IsGenericParam())
  7136. {
  7137. BfGenericParamInstance* checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  7138. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  7139. if (checkGenericParamInst->mTypeConstraint != NULL)
  7140. checkArgType = checkGenericParamInst->mTypeConstraint;
  7141. // if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  7142. // {
  7143. // argMayBeReferenceType = false;
  7144. // }
  7145. // else
  7146. // {
  7147. // argMayBeReferenceType = true;
  7148. // }
  7149. }
  7150. if (checkArgType->IsObjectOrInterface())
  7151. argIsReferenceType = true;
  7152. BfTypeInstance* typeConstraintInst = NULL;
  7153. if (genericParamInst->mTypeConstraint != NULL)
  7154. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  7155. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  7156. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  7157. {
  7158. if ((!ignoreErrors) && (PreFail()))
  7159. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  7160. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7161. return false;
  7162. }
  7163. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  7164. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  7165. {
  7166. if ((!ignoreErrors) && (PreFail()))
  7167. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  7168. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7169. return false;
  7170. }
  7171. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  7172. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argIsReferenceType))
  7173. {
  7174. if ((!ignoreErrors) && (PreFail()))
  7175. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  7176. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7177. return false;
  7178. }
  7179. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum)
  7180. {
  7181. bool isEnum = checkArgType->IsEnum();
  7182. if ((origCheckArgType->IsGenericParam()) && (checkArgType->IsInstanceOf(mCompiler->mEnumTypeDef)))
  7183. isEnum = true;
  7184. if (((checkGenericParamFlags & (BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!isEnum))
  7185. {
  7186. if ((!ignoreErrors) && (PreFail()))
  7187. *errorOut = Fail(StrFormat("The type '%s' must be an enum type in order to use it as parameter '%s' for '%s'",
  7188. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7189. return false;
  7190. }
  7191. }
  7192. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) &&
  7193. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (checkArgType->IsInterface()))
  7194. {
  7195. if ((!ignoreErrors) && (PreFail()))
  7196. *errorOut = Fail(StrFormat("The type '%s' must be an concrete type in order to use it as parameter '%s' for '%s'",
  7197. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7198. return false;
  7199. }
  7200. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Interface) &&
  7201. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsInterface()))
  7202. {
  7203. if ((!ignoreErrors) && (PreFail()))
  7204. *errorOut = Fail(StrFormat("The type '%s' must be an interface type in order to use it as parameter '%s' for '%s'",
  7205. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7206. return false;
  7207. }
  7208. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7209. {
  7210. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  7211. {
  7212. if ((!ignoreErrors) && (PreFail()))
  7213. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  7214. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7215. return false;
  7216. }
  7217. }
  7218. else
  7219. {
  7220. if (checkArgType->IsConstExprValue())
  7221. {
  7222. if ((!ignoreErrors) && (PreFail()))
  7223. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  7224. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7225. return false;
  7226. }
  7227. }
  7228. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  7229. {
  7230. bool canDelete = false;
  7231. if (checkArgType->IsPointer())
  7232. canDelete = true;
  7233. else if (checkArgType->IsObjectOrInterface())
  7234. canDelete = true;
  7235. else if ((checkGenericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var)) != 0)
  7236. canDelete = true;
  7237. if (!canDelete)
  7238. {
  7239. if ((!ignoreErrors) && (PreFail()))
  7240. {
  7241. if (checkArgType->IsGenericParam())
  7242. *errorOut = Fail(StrFormat("Must add 'where %s : delete' constraint in order to use type as parameter '%s' for '%s'",
  7243. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7244. else
  7245. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  7246. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7247. }
  7248. return false;
  7249. }
  7250. }
  7251. if (checkArgType->IsPointer())
  7252. {
  7253. auto ptrType = (BfPointerType*)checkArgType;
  7254. checkArgType = ptrType->mElementType;
  7255. }
  7256. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  7257. {
  7258. bool canAlloc = false;
  7259. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  7260. {
  7261. if (checkTypeInst->IsObjectOrStruct())
  7262. {
  7263. checkTypeInst->mTypeDef->PopulateMemberSets();
  7264. BfMemberSetEntry* entry = NULL;
  7265. BfMethodDef* checkMethodDef = NULL;
  7266. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  7267. if (entry != NULL)
  7268. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  7269. bool hadProtected = false;
  7270. while (checkMethodDef != NULL)
  7271. {
  7272. if (!checkMethodDef->mParams.IsEmpty())
  7273. {
  7274. auto firstParam = checkMethodDef->mParams[0];
  7275. if (((firstParam->mParamKind == BfParamKind_Params) || (firstParam->mParamKind == BfParamKind_AppendIdx) || (firstParam->mParamKind == BfParamKind_VarArgs)) ||
  7276. ((firstParam->mParamDeclaration != NULL) && (firstParam->mParamDeclaration->mInitializer != NULL)))
  7277. {
  7278. // Allow all-default params
  7279. }
  7280. else
  7281. {
  7282. checkMethodDef = checkMethodDef->mNextWithSameName;
  7283. continue;
  7284. }
  7285. }
  7286. if (checkMethodDef->mProtection == BfProtection_Public)
  7287. {
  7288. canAlloc = true;
  7289. break;
  7290. }
  7291. if ((checkMethodDef->mProtection == BfProtection_Protected) || (checkMethodDef->mProtection == BfProtection_ProtectedInternal))
  7292. hadProtected = true;
  7293. checkMethodDef = checkMethodDef->mNextWithSameName;
  7294. }
  7295. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  7296. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  7297. }
  7298. }
  7299. else if (checkArgType->IsGenericParam())
  7300. {
  7301. canAlloc = (checkGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) != 0;
  7302. }
  7303. else if (checkArgType->IsPrimitiveType())
  7304. {
  7305. // Any primitive types and stuff can be allocated
  7306. canAlloc = true;
  7307. }
  7308. if (!canAlloc)
  7309. {
  7310. if ((!ignoreErrors) && (PreFail()))
  7311. {
  7312. if (checkArgType->IsGenericParam())
  7313. *errorOut = Fail(StrFormat("Must add 'where %s : new' constraint in order to use type as parameter '%s' for '%s'",
  7314. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7315. else
  7316. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  7317. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7318. }
  7319. return false;
  7320. }
  7321. }
  7322. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  7323. return true;
  7324. if (genericParamInst->mTypeConstraint != NULL)
  7325. {
  7326. bool constraintMatched = false;
  7327. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7328. {
  7329. if (checkArgType->IsConstExprValue())
  7330. {
  7331. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  7332. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  7333. {
  7334. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  7335. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  7336. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  7337. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  7338. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  7339. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  7340. {
  7341. bool doError = true;
  7342. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  7343. {
  7344. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7345. {
  7346. if (mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue))
  7347. doError = false;
  7348. }
  7349. }
  7350. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_Float) && ((constExprValueType->mValue.mTypeCode == BfTypeCode_Double)))
  7351. {
  7352. doError = false;
  7353. }
  7354. if (doError)
  7355. {
  7356. if ((!ignoreErrors) && (PreFail()))
  7357. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7358. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7359. return false;
  7360. }
  7361. }
  7362. }
  7363. else if (genericParamInst->mTypeConstraint != constExprValueType->mType)
  7364. {
  7365. if ((!ignoreErrors) && (PreFail()))
  7366. *errorOut = Fail(StrFormat("Const generic argument '%s', declared as '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7367. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7368. return false;
  7369. }
  7370. }
  7371. }
  7372. else
  7373. {
  7374. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  7375. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  7376. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7377. if (convCheckConstraint == NULL)
  7378. return false;
  7379. if ((checkArgType->IsMethodRef()) || (checkArgType->IsFunction()))
  7380. {
  7381. if (convCheckConstraint->IsDelegate())
  7382. {
  7383. BfMethodInstance* checkMethodInstance;
  7384. if (checkArgType->IsMethodRef())
  7385. {
  7386. auto methodRefType = (BfMethodRefType*)checkArgType;
  7387. checkMethodInstance = methodRefType->mMethodRef;
  7388. }
  7389. else
  7390. {
  7391. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  7392. }
  7393. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  7394. if (checkMethodInstance->HasExplicitThis() != 0)
  7395. {
  7396. // Don't allow functions with explicit 'this'
  7397. }
  7398. else
  7399. {
  7400. BfExprEvaluator exprEvaluator(this);
  7401. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  7402. constraintMatched = true;
  7403. }
  7404. }
  7405. else if (convCheckConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef))
  7406. constraintMatched = true;
  7407. }
  7408. else if (CanCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  7409. {
  7410. constraintMatched = true;
  7411. }
  7412. else if (origCheckArgType->IsWrappableType())
  7413. {
  7414. if (origCheckArgType->IsSizedArray())
  7415. {
  7416. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  7417. if (convCheckConstraint->IsGenericTypeInstance())
  7418. {
  7419. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  7420. if (convCheckConstraintInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  7421. {
  7422. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  7423. {
  7424. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  7425. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  7426. constraintMatched = true;
  7427. }
  7428. }
  7429. }
  7430. }
  7431. if (!constraintMatched)
  7432. {
  7433. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7434. if (CanCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  7435. constraintMatched = true;
  7436. }
  7437. }
  7438. if (!constraintMatched)
  7439. {
  7440. if ((!ignoreErrors) && (PreFail()))
  7441. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  7442. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  7443. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  7444. return false;
  7445. }
  7446. }
  7447. }
  7448. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  7449. {
  7450. BfType* convCheckConstraint = checkConstraint;
  7451. if (convCheckConstraint->IsUnspecializedType())
  7452. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7453. if (convCheckConstraint == NULL)
  7454. return false;
  7455. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  7456. bool implementsInterface = false;
  7457. if (origCheckArgType != checkArgType)
  7458. {
  7459. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  7460. }
  7461. if (!implementsInterface)
  7462. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  7463. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  7464. {
  7465. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7466. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7467. implementsInterface = true;
  7468. }
  7469. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  7470. {
  7471. auto underlyingType = origCheckArgType->GetUnderlyingType();
  7472. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  7473. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7474. implementsInterface = true;
  7475. }
  7476. if (!implementsInterface)
  7477. {
  7478. if ((!ignoreErrors) && (PreFail()))
  7479. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  7480. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  7481. return false;
  7482. }
  7483. }
  7484. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  7485. {
  7486. auto leftType = checkOpConstraint.mLeftType;
  7487. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  7488. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs, mCurTypeInstance);
  7489. if (leftType != NULL)
  7490. leftType = FixIntUnknown(leftType);
  7491. auto rightType = checkOpConstraint.mRightType;
  7492. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  7493. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs, mCurTypeInstance);
  7494. if (rightType != NULL)
  7495. rightType = FixIntUnknown(rightType);
  7496. BfConstraintState constraintSet;
  7497. constraintSet.mPrevState = mContext->mCurConstraintState;
  7498. constraintSet.mGenericParamInstance = genericParamInst;
  7499. constraintSet.mLeftType = leftType;
  7500. constraintSet.mRightType = rightType;
  7501. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  7502. if (!CheckConstraintState(NULL))
  7503. return false;
  7504. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  7505. {
  7506. BfExprEvaluator exprEvaluator(this);
  7507. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  7508. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7509. //
  7510. {
  7511. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7512. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7513. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  7514. }
  7515. if ((!exprEvaluator.mResult) ||
  7516. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  7517. {
  7518. if ((!ignoreErrors) && (PreFail()))
  7519. {
  7520. if (genericParamInst->mExternType != NULL)
  7521. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  7522. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  7523. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7524. ), checkArgTypeRef);
  7525. else
  7526. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  7527. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7528. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7529. ), checkArgTypeRef);
  7530. }
  7531. return false;
  7532. }
  7533. }
  7534. else
  7535. {
  7536. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7537. StringT<128> failedOpName;
  7538. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  7539. {
  7540. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7541. failedOpName = "implicit conversion from '";
  7542. }
  7543. else
  7544. {
  7545. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7546. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7547. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  7548. {
  7549. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7550. failedOpName = "explicit conversion from '";
  7551. }
  7552. else
  7553. {
  7554. BfExprEvaluator exprEvaluator(this);
  7555. exprEvaluator.mResult = rightValue;
  7556. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  7557. if ((!exprEvaluator.mResult) ||
  7558. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  7559. {
  7560. failedOpName += "unary operation '";
  7561. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  7562. }
  7563. }
  7564. }
  7565. if (!failedOpName.IsEmpty())
  7566. {
  7567. if ((!ignoreErrors) && (PreFail()))
  7568. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  7569. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7570. failedOpName.c_str(), TypeToString(rightType).c_str()
  7571. ), checkArgTypeRef);
  7572. return false;
  7573. }
  7574. }
  7575. }
  7576. return true;
  7577. }
  7578. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  7579. {
  7580. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  7581. {
  7582. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  7583. return genericParamType;
  7584. }
  7585. auto genericParamType = new BfGenericParamType();
  7586. genericParamType->mContext = mContext;
  7587. genericParamType->mGenericParamKind = paramKind;
  7588. genericParamType->mGenericParamIdx = paramIdx;
  7589. PopulateType(genericParamType);
  7590. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  7591. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  7592. BfResolvedTypeSet::LookupContext lookupCtx;
  7593. lookupCtx.mModule = this;
  7594. BfResolvedTypeSet::EntryRef typeEntry;
  7595. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  7596. BF_ASSERT(inserted);
  7597. typeEntry->mValue = genericParamType;
  7598. return genericParamType;
  7599. }
  7600. static int sValueFromExprIdx = 0;
  7601. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  7602. {
  7603. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  7604. if ((result) && (!ignoreNullable))
  7605. {
  7606. if (result.mType->IsVar())
  7607. return result;
  7608. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  7609. //TODO: Make this work, needed for 'void' and such
  7610. BfType* nullableType = NULL;
  7611. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  7612. {
  7613. BfTypeVector typeVec;
  7614. typeVec.push_back(result.mType);
  7615. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  7616. BF_ASSERT(nullableType != NULL);
  7617. }
  7618. // Go back to start and do any setup we need
  7619. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7620. BfTypedValue nullableTypedValue;
  7621. if (nullableType != NULL)
  7622. {
  7623. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  7624. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  7625. GetConstValue(nullableType->mSize), nullableType->mAlign);
  7626. }
  7627. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7628. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  7629. mBfIRBuilder->SetInsertPoint(notNullBB);
  7630. result = LoadValue(result);
  7631. if (nullableTypedValue)
  7632. {
  7633. auto elementType = nullableType->GetUnderlyingType();
  7634. if (elementType->IsVar())
  7635. {
  7636. // Do nothing
  7637. }
  7638. else if (elementType->IsValuelessType())
  7639. {
  7640. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  7641. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  7642. }
  7643. else
  7644. {
  7645. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  7646. mBfIRBuilder->CreateAlignedStore(result.mValue, ptrValue, result.mType->mAlign);
  7647. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  7648. mBfIRBuilder->CreateAlignedStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue, 1);
  7649. }
  7650. result = nullableTypedValue;
  7651. }
  7652. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7653. AddBasicBlock(pendingNullCond->mDoneBB);
  7654. if (nullableType == NULL)
  7655. {
  7656. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  7657. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  7658. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  7659. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  7660. {
  7661. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  7662. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  7663. }
  7664. result.mValue = phi;
  7665. }
  7666. }
  7667. else
  7668. {
  7669. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7670. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7671. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7672. AddBasicBlock(pendingNullCond->mDoneBB);
  7673. }
  7674. delete mCurMethodState->mPendingNullConditional;
  7675. mCurMethodState->mPendingNullConditional = NULL;
  7676. return result;
  7677. }
  7678. BF_NOINLINE void BfModule::EvaluateWithNewConditionalScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  7679. {
  7680. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  7681. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData);
  7682. if (mCurMethodState != NULL)
  7683. {
  7684. deferredLocalAssignData.mIsIfCondition = true;
  7685. deferredLocalAssignData.mIfMayBeSkipped = true;
  7686. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  7687. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  7688. mCurMethodState->mDeferredLocalAssignData = &deferredLocalAssignData;
  7689. }
  7690. BfScopeData newScope;
  7691. newScope.mOuterIsConditional = true;
  7692. newScope.mAllowTargeting = false;
  7693. if (mCurMethodState != NULL)
  7694. {
  7695. mCurMethodState->AddScope(&newScope);
  7696. NewScopeState(true, false);
  7697. }
  7698. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7699. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  7700. if (mCurMethodState != NULL)
  7701. RestoreScopeState();
  7702. }
  7703. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7704. {
  7705. //
  7706. {
  7707. BP_ZONE("CreateValueFromExpression:CheckStack");
  7708. StackHelper stackHelper;
  7709. if (!stackHelper.CanStackExpand(64 * 1024))
  7710. {
  7711. BfTypedValue result;
  7712. if (!stackHelper.Execute([&]()
  7713. {
  7714. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7715. }))
  7716. {
  7717. Fail("Expression too complex to compile", expr);
  7718. }
  7719. return result;
  7720. }
  7721. }
  7722. BP_ZONE("BfModule::CreateValueFromExpression");
  7723. if (outOrigType != NULL)
  7724. *outOrigType = NULL;
  7725. exprEvaluator.mExpectingType = wantTypeRef;
  7726. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7727. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  7728. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  7729. {
  7730. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope->mScopeKind != BfScopeKind_StatementTarget_Conditional))
  7731. {
  7732. EvaluateWithNewConditionalScope(exprEvaluator, expr, flags);
  7733. }
  7734. else
  7735. {
  7736. SetAndRestoreValue<bool> prevIsConditional(mCurMethodState->mCurScope->mIsConditional, true);
  7737. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7738. }
  7739. }
  7740. else
  7741. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7742. if (!exprEvaluator.mResult)
  7743. {
  7744. if ((flags & BfEvalExprFlags_InferReturnType) != 0)
  7745. return exprEvaluator.mResult;
  7746. if (!mCompiler->mPassInstance->HasFailed())
  7747. {
  7748. if (PreFail())
  7749. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  7750. }
  7751. return BfTypedValue();
  7752. }
  7753. auto typedVal = exprEvaluator.mResult;
  7754. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  7755. {
  7756. BF_ASSERT(typedVal.mType->IsGenericParam());
  7757. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  7758. bool handled = false;
  7759. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7760. {
  7761. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  7762. if (genericTypeConstraint != NULL)
  7763. {
  7764. auto underlyingConstraint = genericTypeConstraint;
  7765. if ((underlyingConstraint != NULL) && (underlyingConstraint->IsBoxed()))
  7766. underlyingConstraint = underlyingConstraint->GetUnderlyingType();
  7767. if (underlyingConstraint != NULL)
  7768. {
  7769. BfTypedValue result;
  7770. result.mKind = BfTypedValueKind_Value;
  7771. result.mType = genericTypeConstraint;
  7772. result.mValue = mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(underlyingConstraint));
  7773. typedVal = result;
  7774. handled = true;
  7775. }
  7776. }
  7777. }
  7778. if (!handled)
  7779. {
  7780. //Fail("Only const generic parameters can be used as values", expr);
  7781. AssertErrorState();
  7782. return BfTypedValue();
  7783. }
  7784. }
  7785. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  7786. FixIntUnknown(typedVal);
  7787. if (!mBfIRBuilder->mIgnoreWrites)
  7788. FixValueActualization(typedVal);
  7789. exprEvaluator.CheckResultForReading(typedVal);
  7790. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  7791. {
  7792. if ((flags & BfEvalExprFlags_NoCast) == 0)
  7793. {
  7794. // Only allow a 'ref' type if we have an explicit 'ref' operator
  7795. bool allowRef = false;
  7796. BfAstNode* checkExpr = expr;
  7797. while (checkExpr != NULL)
  7798. {
  7799. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  7800. checkExpr = parenExpr->mExpression;
  7801. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  7802. {
  7803. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  7804. allowRef = true;
  7805. break;
  7806. }
  7807. if (auto block = BfNodeDynCast<BfBlock>(checkExpr))
  7808. {
  7809. if (block->mChildArr.mSize == 0)
  7810. break;
  7811. checkExpr = block->mChildArr.back();
  7812. }
  7813. else
  7814. break;
  7815. }
  7816. if (!allowRef)
  7817. typedVal = RemoveRef(typedVal);
  7818. }
  7819. }
  7820. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  7821. {
  7822. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsDataIncomplete()) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  7823. {
  7824. BF_ASSERT(!typedVal.mValue.IsFake());
  7825. }
  7826. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7827. }
  7828. if (wantTypeRef != NULL)
  7829. {
  7830. if (outOrigType != NULL)
  7831. *outOrigType = typedVal.mType;
  7832. if (((flags & BfEvalExprFlags_NoCast) == 0) && (!wantTypeRef->IsVar()))
  7833. {
  7834. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  7835. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  7836. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  7837. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  7838. if (!typedVal)
  7839. return typedVal;
  7840. }
  7841. if (exprEvaluator.mIsVolatileReference)
  7842. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7843. }
  7844. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  7845. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7846. return typedVal;
  7847. }
  7848. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7849. {
  7850. BfExprEvaluator exprEvaluator(this);
  7851. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7852. }
  7853. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  7854. {
  7855. BfExprEvaluator exprEvaluator(this);
  7856. exprEvaluator.Evaluate(expr);
  7857. if (!exprEvaluator.mResult)
  7858. {
  7859. Fail("Invalid expression type", expr);
  7860. return BfTypedValue();
  7861. }
  7862. if (!exprEvaluator.mResult.IsAddr())
  7863. {
  7864. Fail("Cannot assign to value", expr);
  7865. return BfTypedValue();
  7866. }
  7867. return exprEvaluator.mResult;
  7868. }
  7869. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  7870. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  7871. {
  7872. auto typeInstance = typedValue.mType->ToTypeInstance();
  7873. if (zeroMemory)
  7874. {
  7875. int zeroAlign = typedValue.mType->mAlign;
  7876. if (typeInstance != NULL)
  7877. zeroAlign = typeInstance->mInstAlign;
  7878. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  7879. }
  7880. if (!typedValue.mType->IsObject())
  7881. {
  7882. return;
  7883. }
  7884. if ((scopeData == NULL) && (mCurMethodState != NULL))
  7885. return; // Handled in heap alloc funcs
  7886. auto typeDef = typeInstance->mTypeDef;
  7887. mBfIRBuilder->PopulateType(typedValue.mType);
  7888. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  7889. bool isAutocomplete = mCompiler->IsAutocomplete();
  7890. BfIRValue vDataRef;
  7891. if (!isAutocomplete)
  7892. {
  7893. vDataRef = GetClassVDataPtr(typeInstance);
  7894. }
  7895. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  7896. auto ptrType = CreatePointerType(i8Type);
  7897. auto ptrPtrType = CreatePointerType(ptrType);
  7898. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  7899. PopulateType(ptrType, BfPopulateType_Declaration);
  7900. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  7901. if (!isAutocomplete)
  7902. {
  7903. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  7904. {
  7905. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7906. SizedArray<BfIRValue, 4> llvmArgs;
  7907. llvmArgs.push_back(objectPtr);
  7908. llvmArgs.push_back(vDataRef);
  7909. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  7910. if (objectStackInitMethod)
  7911. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  7912. }
  7913. else
  7914. {
  7915. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  7916. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  7917. mBfIRBuilder->CreateStore(srcVal, destAddr);
  7918. }
  7919. }
  7920. }
  7921. bool BfModule::IsAllocatorAligned()
  7922. {
  7923. if (mCompiler->mOptions.mMallocLinkName == "StompAlloc")
  7924. return false;
  7925. return true;
  7926. }
  7927. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  7928. {
  7929. BfIRValue result;
  7930. BfType* ptrType;
  7931. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  7932. ptrType = type;
  7933. else
  7934. ptrType = CreatePointerType(type);
  7935. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  7936. {
  7937. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7938. SizedArray<BfExpression*, 2> argExprs;
  7939. BfTypedValueExpression typedValueExpr;
  7940. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  7941. typedValueExpr.mRefNode = refNode;
  7942. argExprs.push_back(&typedValueExpr);
  7943. BfTypedValueExpression appendSizeValueExpr;
  7944. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  7945. appendSizeValueExpr.mRefNode = refNode;
  7946. argExprs.push_back(&appendSizeValueExpr);
  7947. BfExprEvaluator exprEvaluator(this);
  7948. BfTypedValue allocResult;
  7949. if (allocTarget.mScopedInvocationTarget != NULL)
  7950. {
  7951. SizedArray<BfTypeReference*, 2> genericArgs;
  7952. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, BfMethodGenericArguments());
  7953. allocResult = LoadValue(exprEvaluator.mResult);
  7954. }
  7955. else if (allocTarget.mCustomAllocator)
  7956. {
  7957. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  7958. if (customTypeInst == NULL)
  7959. {
  7960. if (allocTarget.mCustomAllocator.mType->IsStructPtr())
  7961. customTypeInst = allocTarget.mCustomAllocator.mType->GetUnderlyingType()->ToTypeInstance();
  7962. }
  7963. if (customTypeInst == NULL)
  7964. {
  7965. Fail(StrFormat("Type '%s' cannot be used as a custom allocator", TypeToString(allocTarget.mCustomAllocator.mType).c_str()), refNode);
  7966. }
  7967. else
  7968. {
  7969. BfTypedValueExpression typeValueExpr;
  7970. String allocMethodName = "Alloc";
  7971. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  7972. {
  7973. allocMethodName = "AllocTyped";
  7974. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  7975. auto typeRefVal = CreateTypeDataRef(type);
  7976. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  7977. typeValueExpr.mRefNode = refNode;
  7978. argExprs.Insert(0, &typeValueExpr);
  7979. }
  7980. if (HasMixin(customTypeInst, allocMethodName, 2))
  7981. {
  7982. BfSizedArray<BfExpression*> argExprArr;
  7983. argExprArr.mSize = (int)argExprs.size();
  7984. argExprArr.mVals = &argExprs[0];
  7985. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  7986. allocResult = exprEvaluator.GetResult();
  7987. }
  7988. else
  7989. {
  7990. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  7991. BfResolvedArgs argValues(&sizedArgExprs);
  7992. exprEvaluator.ResolveArgValues(argValues);
  7993. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  7994. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, BfMethodGenericArguments());
  7995. }
  7996. }
  7997. }
  7998. if (allocResult)
  7999. {
  8000. if (allocResult.mType->IsVoidPtr())
  8001. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  8002. else
  8003. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  8004. return result;
  8005. }
  8006. }
  8007. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  8008. return result;
  8009. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8010. {
  8011. BfIRValue allocData = GetDbgRawAllocData(type);
  8012. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  8013. SizedArray<BfIRValue, 2> llvmArgs;
  8014. llvmArgs.push_back(sizeValue);
  8015. llvmArgs.push_back(allocData);
  8016. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  8017. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8018. }
  8019. BfModuleMethodInstance moduleMethodInstance;
  8020. moduleMethodInstance = GetInternalMethod("Malloc");
  8021. SizedArray<BfIRValue, 1> llvmArgs;
  8022. llvmArgs.push_back(sizeValue);
  8023. auto func = moduleMethodInstance.mFunc;
  8024. if ((!func) || (func.IsFake()))
  8025. {
  8026. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  8027. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  8028. }
  8029. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  8030. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  8031. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  8032. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8033. return result;
  8034. }
  8035. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  8036. {
  8037. if (type->IsStruct())
  8038. {
  8039. auto typeInstance = type->ToTypeInstance();
  8040. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  8041. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8042. }
  8043. else if (type->IsObjectOrInterface())
  8044. {
  8045. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8046. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  8047. BF_ASSERT(moduleMethodInst.mFunc);
  8048. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8049. }
  8050. else
  8051. {
  8052. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8053. BfExprEvaluator exprEvaluator(this);
  8054. SizedArray<BfResolvedArg, 1> resolvedArgs;
  8055. BfResolvedArg resolvedArg;
  8056. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  8057. resolvedArgs.Add(resolvedArg);
  8058. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, BfMethodGenericArguments());
  8059. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  8060. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  8061. BF_ASSERT(moduleMethodInst.mFunc);
  8062. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8063. }
  8064. return BfIRValue();
  8065. }
  8066. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  8067. {
  8068. BfIRValue allocDataValue;
  8069. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  8070. return allocDataValue;
  8071. BfIRValue markFuncPtr;
  8072. if (type->WantsGCMarking())
  8073. markFuncPtr = GetMarkFuncPtr(type);
  8074. else
  8075. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8076. BfIRValue typeDataRef = CreateTypeDataRef(type);
  8077. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  8078. BfTypeInstance* typeInstance = type->ToTypeInstance();
  8079. if (typeInstance == NULL)
  8080. {
  8081. typeInstance = GetWrappedStructType(type);
  8082. if (typeInstance != NULL)
  8083. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8084. }
  8085. if (typeInstance != NULL)
  8086. PopulateType(typeInstance);
  8087. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8088. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  8089. {
  8090. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8091. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8092. }
  8093. SizedArray<BfIRValue, 2> dataValues;
  8094. dataValues.Add(mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  8095. dataValues.Add(typeDataRef);
  8096. dataValues.Add(markFuncPtr);
  8097. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  8098. BfIRValue dataStruct = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  8099. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  8100. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  8101. return allocDataValue;
  8102. }
  8103. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  8104. {
  8105. BP_ZONE("AllocFromType");
  8106. BfScopeData* scopeData = allocTarget.mScopeData;
  8107. BF_ASSERT(!type->IsVar());
  8108. auto typeInstance = type->ToTypeInstance();
  8109. if ((typeInstance == NULL) && (type->IsGenericParam()))
  8110. typeInstance = mContext->mBfObjectType;
  8111. bool isHeapAlloc = scopeData == NULL;
  8112. bool isScopeAlloc = scopeData != NULL;
  8113. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  8114. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  8115. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  8116. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  8117. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  8118. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  8119. {
  8120. BfPointerType* ptrType = CreatePointerType(type);
  8121. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  8122. return val;
  8123. }
  8124. if (typeInstance != NULL)
  8125. mBfIRBuilder->PopulateType(typeInstance);
  8126. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  8127. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  8128. {
  8129. return mBfIRBuilder->GetFakeVal();
  8130. }
  8131. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8132. BfIRValue sizeValue;
  8133. BfIRType allocType = mBfIRBuilder->MapType(type);
  8134. int allocSize = type->mSize;
  8135. int allocAlign = type->mAlign;
  8136. if (typeInstance != NULL)
  8137. {
  8138. if ((!mBfIRBuilder->mIgnoreWrites) && (!mIsComptimeModule))
  8139. typeInstance->mHasBeenInstantiated = true;
  8140. allocSize = typeInstance->mInstSize;
  8141. allocAlign = typeInstance->mInstAlign;
  8142. //if (typeInstance->IsEnum())
  8143. //allocType = typeInstance->mIRType;
  8144. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  8145. }
  8146. if (alignOverride != -1)
  8147. allocAlign = alignOverride;
  8148. // The "dynSize" cases:
  8149. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  8150. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  8151. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  8152. // though we'd expect their stack space to be released
  8153. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  8154. {
  8155. MarkDynStack(scopeData);
  8156. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8157. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  8158. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  8159. BfType* voidPtrType = CreatePointerType(voidType);
  8160. if (!mCurMethodState->mDynStackRevIdx)
  8161. {
  8162. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  8163. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8164. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8165. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  8166. mBfIRBuilder->ClearDebugLocation(storeInst);
  8167. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8168. }
  8169. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  8170. auto bytePtrType = CreatePointerType(byteType);
  8171. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  8172. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  8173. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8174. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8175. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  8176. mBfIRBuilder->ClearDebugLocation(storeInst);
  8177. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  8178. mBfIRBuilder->ClearDebugLocation(storeInst);
  8179. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8180. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  8181. if (IsTargetingBeefBackend())
  8182. {
  8183. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  8184. // to ensure there isn't any register collision during looping is just to not allow it to
  8185. // bind to a register at all
  8186. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  8187. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  8188. }
  8189. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  8190. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  8191. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  8192. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  8193. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  8194. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  8195. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  8196. mBfIRBuilder->AddBlock(verCheckBB);
  8197. mBfIRBuilder->SetInsertPoint(verCheckBB);
  8198. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  8199. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  8200. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  8201. mBfIRBuilder->AddBlock(resizeBB);
  8202. mBfIRBuilder->SetInsertPoint(resizeBB);
  8203. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8204. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  8205. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  8206. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  8207. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  8208. mBfIRBuilder->CreateBr(endBB);
  8209. mBfIRBuilder->AddBlock(endBB);
  8210. mBfIRBuilder->SetInsertPoint(endBB);
  8211. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  8212. };
  8213. if (isScopeAlloc)
  8214. {
  8215. if (arraySize)
  8216. {
  8217. bool isConstantArraySize = arraySize.IsConst();
  8218. if (isRawArrayAlloc)
  8219. {
  8220. BfPointerType* ptrType = CreatePointerType(type);
  8221. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8222. {
  8223. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8224. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  8225. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  8226. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  8227. }
  8228. else
  8229. {
  8230. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8231. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  8232. if (!isDynAlloc)
  8233. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8234. else
  8235. {
  8236. MarkDynStack(scopeData);
  8237. SaveStackState(scopeData);
  8238. }
  8239. int typeSize = type->GetStride();
  8240. BfIRValue allocaInst;
  8241. BfIRValue result;
  8242. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  8243. {
  8244. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  8245. result = allocaInst;
  8246. }
  8247. else
  8248. {
  8249. if (typeInstance->IsStruct())
  8250. typeSize = typeInstance->GetInstStride();
  8251. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  8252. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  8253. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8254. auto ptrType = CreatePointerType(typeInstance);
  8255. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  8256. if (!isDynAlloc)
  8257. mBfIRBuilder->ClearDebugLocation(result);
  8258. }
  8259. if (!isDynAlloc)
  8260. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8261. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8262. if (!isDynAlloc)
  8263. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8264. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  8265. if (arraySize.IsConst())
  8266. {
  8267. auto constant = mBfIRBuilder->GetConstant(arraySize);
  8268. if (constant->mInt64 == 0)
  8269. noDtorCall = true;
  8270. }
  8271. if (!noDtorCall)
  8272. {
  8273. bool isConstSize = arraySize.IsConst();
  8274. BfIRBlock clearBlock;
  8275. BfIRBlock contBlock;
  8276. bool wantsDeinit = ((!IsOptimized()) && (!mIsComptimeModule) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly));
  8277. if (wantsDeinit)
  8278. {
  8279. BfIRBlock prevBlock;
  8280. if (!isConstSize)
  8281. {
  8282. clearBlock = mBfIRBuilder->CreateBlock("clear");
  8283. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  8284. prevBlock = mBfIRBuilder->GetInsertBlock();
  8285. mBfIRBuilder->AddBlock(clearBlock);
  8286. mBfIRBuilder->SetInsertPoint(clearBlock);
  8287. }
  8288. auto deferredCall = AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  8289. if (!isConstSize)
  8290. {
  8291. mBfIRBuilder->CreateBr(contBlock);
  8292. mBfIRBuilder->SetInsertPoint(prevBlock);
  8293. if (deferredCall != NULL)
  8294. {
  8295. // Zero out size args
  8296. for (int i = 1; i < deferredCall->mModuleMethodInstance.mMethodInstance->GetParamCount(); i++)
  8297. {
  8298. auto scopedArg = deferredCall->mScopeArgs[i];
  8299. if (scopedArg != deferredCall->mOrigScopeArgs[i])
  8300. mBfIRBuilder->CreateStore(GetDefaultValue(deferredCall->mModuleMethodInstance.mMethodInstance->GetParamType(i)), deferredCall->mScopeArgs[i]);
  8301. }
  8302. }
  8303. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  8304. mBfIRBuilder->AddBlock(contBlock);
  8305. mBfIRBuilder->SetInsertPoint(contBlock);
  8306. }
  8307. }
  8308. }
  8309. return result;
  8310. }
  8311. }
  8312. else
  8313. {
  8314. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8315. {
  8316. // Generate and check new size
  8317. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8318. auto firstElementField = &arrayType->mFieldInstances.back();
  8319. int arrayClassSize = firstElementField->mDataOffset;
  8320. sizeValue = GetConstValue(arrayClassSize);
  8321. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8322. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8323. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  8324. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  8325. if (!noDtorCall)
  8326. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8327. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8328. return typedVal.mValue;
  8329. }
  8330. else
  8331. {
  8332. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8333. auto firstElementField = &arrayType->mFieldInstances.back();
  8334. if (!type->IsValuelessType())
  8335. {
  8336. int arrayClassSize = firstElementField->mDataOffset;
  8337. sizeValue = GetConstValue(arrayClassSize);
  8338. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8339. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8340. }
  8341. else
  8342. sizeValue = GetConstValue(arrayType->mInstSize);
  8343. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8344. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8345. if (!isDynAlloc)
  8346. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8347. else
  8348. {
  8349. MarkDynStack(scopeData);
  8350. SaveStackState(scopeData);
  8351. }
  8352. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  8353. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8354. if (!isDynAlloc)
  8355. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8356. auto allocaBlock = mBfIRBuilder->GetInsertBlock();
  8357. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8358. BfTypedValue typedVal;
  8359. if (!isDynAlloc)
  8360. {
  8361. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8362. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8363. mBfIRBuilder->ClearDebugLocation_Last();
  8364. mBfIRBuilder->SetInsertPoint(prevBlock);
  8365. allocaBlock = mCurMethodState->mIRInitBlock;
  8366. }
  8367. else
  8368. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8369. if (!noDtorCall)
  8370. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true, allocaBlock);
  8371. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8372. return typedVal.mValue;
  8373. }
  8374. }
  8375. }
  8376. else if (appendSizeValue)
  8377. {
  8378. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  8379. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  8380. // use the "dynSize" version conservatively
  8381. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8382. {
  8383. // Generate and check new size
  8384. sizeValue = GetConstValue(typeInstance->mInstSize);
  8385. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8386. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  8387. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  8388. if (!noDtorCall)
  8389. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  8390. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8391. return typedVal.mValue;
  8392. }
  8393. else // stack alloc, unlooped, with append
  8394. {
  8395. sizeValue = GetConstValue(typeInstance->mInstSize);
  8396. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8397. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8398. bool wasDynAlloc = isDynAlloc;
  8399. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8400. if (!isDynAlloc)
  8401. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8402. else
  8403. {
  8404. MarkDynStack(scopeData);
  8405. SaveStackState(scopeData);
  8406. }
  8407. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  8408. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  8409. if (!isDynAlloc)
  8410. {
  8411. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8412. }
  8413. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8414. bool mayBeLarge = false;
  8415. if (sizeValue.IsConst())
  8416. {
  8417. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  8418. if (constantInt->mInt64 >= 4096)
  8419. mayBeLarge = true;
  8420. }
  8421. else
  8422. mayBeLarge = true;
  8423. if (((type->IsObject() && (!mayBeLarge))) ||
  8424. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8425. ((zeroMemory) && (!mayBeLarge)))
  8426. {
  8427. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8428. }
  8429. BfIRValue castedVal;
  8430. if (!isDynAlloc)
  8431. {
  8432. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8433. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8434. mBfIRBuilder->ClearDebugLocation(castedVal);
  8435. mBfIRBuilder->SetInsertPoint(prevBlock);
  8436. if (WantsLifetimes())
  8437. {
  8438. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8439. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8440. }
  8441. }
  8442. else
  8443. {
  8444. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8445. }
  8446. auto typedVal = BfTypedValue(castedVal, typeInstance);
  8447. if (!noDtorCall)
  8448. {
  8449. bool doCondAlloca = false;
  8450. if (!IsTargetingBeefBackend())
  8451. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  8452. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  8453. }
  8454. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8455. return typedVal.mValue;
  8456. }
  8457. }
  8458. else // "Normal" stack alloc
  8459. {
  8460. BF_ASSERT(!sizeValue);
  8461. //TODO: If sizeValue is a constant then do this in the head IR builder
  8462. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8463. if (!isLoopedAlloc)
  8464. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8465. else
  8466. {
  8467. MarkDynStack(scopeData);
  8468. SaveStackState(scopeData);
  8469. }
  8470. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  8471. if (!isLoopedAlloc)
  8472. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8473. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8474. bool mayBeLarge = allocSize >= 4096;
  8475. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  8476. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8477. ((zeroMemory) && (!mayBeLarge)))
  8478. {
  8479. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  8480. // and memset is always safe
  8481. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8482. }
  8483. auto typedVal = BfTypedValue(allocaInst, type);
  8484. if (!isLoopedAlloc)
  8485. {
  8486. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8487. mBfIRBuilder->SetInsertPoint(prevBlock);
  8488. if (WantsLifetimes())
  8489. {
  8490. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8491. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8492. }
  8493. }
  8494. if (!noDtorCall)
  8495. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8496. if (typeInstance != NULL)
  8497. {
  8498. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  8499. }
  8500. else
  8501. {
  8502. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  8503. }
  8504. return allocaInst;
  8505. }
  8506. }
  8507. else if (arraySize)
  8508. {
  8509. if (isRawArrayAlloc)
  8510. {
  8511. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8512. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  8513. }
  8514. else
  8515. {
  8516. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8517. typeInstance = arrayType;
  8518. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8519. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8520. appendSizeValue = elementDataSize;
  8521. if (!type->IsSizeAligned())
  8522. {
  8523. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  8524. }
  8525. }
  8526. }
  8527. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  8528. {
  8529. auto vDataRef = GetClassVDataPtr(typeInstance);
  8530. BfIRValue result;
  8531. bool isResultInitialized = false;
  8532. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8533. if (typeInstance->mTypeOptionsIdx != -1)
  8534. {
  8535. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8536. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8537. }
  8538. if (mIsComptimeModule)
  8539. stackCount = 0;
  8540. if (!sizeValue)
  8541. sizeValue = GetConstValue(typeInstance->mInstSize);
  8542. if (appendSizeValue)
  8543. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8544. BfIRValue origSizeValue = sizeValue;
  8545. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  8546. if (isAllocEx)
  8547. {
  8548. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  8549. if (prepareStackTraceMethod)
  8550. {
  8551. SizedArray<BfIRValue, 2> irArgs;
  8552. irArgs.Add(sizeValue);
  8553. irArgs.Add(GetConstValue(stackCount));
  8554. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  8555. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  8556. }
  8557. }
  8558. if (allocTarget.mCustomAllocator)
  8559. {
  8560. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8561. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  8562. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  8563. {
  8564. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8565. mBfIRBuilder->PopulateType(classVDataType);
  8566. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8567. mBfIRBuilder->PopulateType(typeInstType);
  8568. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  8569. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  8570. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  8571. BfTypedValueExpression typedValueExpr;
  8572. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  8573. typedValueExpr.mRefNode = allocTarget.mRefNode;
  8574. BfExprEvaluator exprEvaluator(this);
  8575. SizedArray<BfExpression*, 2> argExprs;
  8576. argExprs.push_back(&typedValueExpr);
  8577. BfTypedValueExpression sizeValueExpr;
  8578. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  8579. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  8580. argExprs.push_back(&sizeValueExpr);
  8581. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8582. BfResolvedArgs argValues(&sizedArgExprs);
  8583. exprEvaluator.ResolveArgValues(argValues);
  8584. exprEvaluator.mNoBind = true;
  8585. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, BfMethodGenericArguments());
  8586. if (allocResult)
  8587. {
  8588. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  8589. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  8590. else
  8591. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  8592. isResultInitialized = true;
  8593. }
  8594. }
  8595. }
  8596. bool wasAllocated = false;
  8597. if (!result)
  8598. {
  8599. if (hasCustomAllocator)
  8600. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  8601. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8602. {
  8603. SizedArray<BfIRValue, 4> llvmArgs;
  8604. llvmArgs.push_back(sizeValue);
  8605. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8606. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8607. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8608. wasAllocated = true;
  8609. }
  8610. }
  8611. if (result)
  8612. {
  8613. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8614. {
  8615. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  8616. SizedArray<BfIRValue, 4> llvmArgs;
  8617. llvmArgs.push_back(objectPtr);
  8618. llvmArgs.push_back(origSizeValue);
  8619. llvmArgs.push_back(vDataRef);
  8620. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  8621. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  8622. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  8623. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  8624. if (wasAllocated)
  8625. {
  8626. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  8627. auto bytePtrType = CreatePointerType(byteType);
  8628. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  8629. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  8630. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  8631. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  8632. }
  8633. }
  8634. else
  8635. {
  8636. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  8637. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8638. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  8639. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  8640. }
  8641. }
  8642. else
  8643. {
  8644. if ((mBfIRBuilder->mIgnoreWrites) ||
  8645. ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)))
  8646. return GetDefaultValue(typeInstance);
  8647. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8648. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  8649. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8650. {
  8651. SizedArray<BfIRValue, 4> llvmArgs;
  8652. llvmArgs.push_back(vData);
  8653. llvmArgs.push_back(sizeValue);
  8654. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  8655. llvmArgs.push_back(GetConstValue(stackCount));
  8656. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  8657. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  8658. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8659. }
  8660. else
  8661. {
  8662. SizedArray<BfIRValue, 4> llvmArgs;
  8663. llvmArgs.push_back(sizeValue);
  8664. BfIRFunction irFunc;
  8665. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8666. {
  8667. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  8668. irFunc = moduleMethodInstance.mFunc;
  8669. }
  8670. if (!irFunc)
  8671. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8672. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8673. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  8674. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  8675. if (mIsComptimeModule)
  8676. {
  8677. vdataPtr = mBfIRBuilder->CreateBitCast(vdataPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance())));
  8678. }
  8679. mBfIRBuilder->CreateStore(vData, vdataPtr);
  8680. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8681. }
  8682. }
  8683. if ((zeroMemory) && (arraySize))
  8684. {
  8685. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8686. typeInstance = arrayType;
  8687. auto firstElementField = &arrayType->mFieldInstances.back();
  8688. int arrayClassSize = firstElementField->mDataOffset;
  8689. BfIRValue elementDataSize;
  8690. bool skipZero = false;
  8691. if (arraySize.IsConst())
  8692. {
  8693. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8694. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8695. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  8696. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  8697. if (constVal->mInt64 <= 0)
  8698. skipZero = true;
  8699. }
  8700. else
  8701. {
  8702. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  8703. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8704. }
  8705. if (!skipZero)
  8706. {
  8707. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8708. auto ptrType = CreatePointerType(i8Type);
  8709. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  8710. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  8711. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  8712. appendSizeValue = elementDataSize;
  8713. }
  8714. }
  8715. return result;
  8716. }
  8717. else
  8718. {
  8719. if (!sizeValue)
  8720. sizeValue = GetConstValue(allocSize);
  8721. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  8722. }
  8723. }
  8724. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  8725. {
  8726. if ((type == NULL) || (refNode == NULL))
  8727. return;
  8728. auto typeInstance = type->ToTypeInstance();
  8729. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  8730. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  8731. }
  8732. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  8733. {
  8734. if (align <= 1)
  8735. return;
  8736. if (sizeMultiple == 0)
  8737. sizeMultiple = align;
  8738. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  8739. {
  8740. if (!IsAllocatorAligned())
  8741. {
  8742. // Don't align
  8743. }
  8744. else if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  8745. {
  8746. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8747. BF_ASSERT(localVar->mName == "appendIdx");
  8748. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  8749. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8750. if (align > 1)
  8751. {
  8752. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8753. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8754. }
  8755. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  8756. }
  8757. else
  8758. {
  8759. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  8760. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  8761. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  8762. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8763. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8764. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  8765. }
  8766. }
  8767. if (mCurMethodState->mCurAppendAlign == 0)
  8768. mCurMethodState->mCurAppendAlign = sizeMultiple;
  8769. else
  8770. {
  8771. if (sizeMultiple % align == 0)
  8772. mCurMethodState->mCurAppendAlign = align;
  8773. else
  8774. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  8775. }
  8776. }
  8777. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  8778. {
  8779. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8780. BF_ASSERT(localVar->mName == "appendIdx");
  8781. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  8782. BfIRValue retValue;
  8783. BfTypeInstance* retTypeInstance = NULL;
  8784. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  8785. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  8786. if (arraySize)
  8787. {
  8788. if (isRawArrayAlloc)
  8789. {
  8790. EmitAppendAlign(type->mAlign);
  8791. BfPointerType* ptrType = CreatePointerType(type);
  8792. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8793. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8794. if (mSystem->mPtrSize != 4)
  8795. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8796. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8797. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8798. if (zeroMemory)
  8799. {
  8800. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  8801. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  8802. }
  8803. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  8804. }
  8805. else
  8806. {
  8807. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8808. EmitAppendAlign(arrayType->mAlign, type->mSize);
  8809. auto firstElementField = &arrayType->mFieldInstances.back();
  8810. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  8811. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  8812. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8813. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8814. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8815. if (mSystem->mPtrSize != 4)
  8816. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8817. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8818. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8819. if (zeroMemory)
  8820. {
  8821. // Only zero out the actual elements
  8822. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  8823. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  8824. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  8825. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  8826. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  8827. }
  8828. retTypeInstance = arrayType;
  8829. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  8830. }
  8831. }
  8832. else
  8833. {
  8834. auto typeInst = type->ToTypeInstance();
  8835. BfIRValue sizeValue;
  8836. BfIRType toType;
  8837. if (typeInst != NULL)
  8838. {
  8839. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  8840. sizeValue = GetConstValue(typeInst->mInstSize);
  8841. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  8842. }
  8843. else
  8844. {
  8845. EmitAppendAlign(type->mAlign, type->mSize);
  8846. sizeValue = GetConstValue(type->mSize);
  8847. auto toPtrType = CreatePointerType(type);
  8848. toType = mBfIRBuilder->MapType(toPtrType);
  8849. }
  8850. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8851. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8852. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8853. retTypeInstance = typeInst;
  8854. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  8855. }
  8856. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  8857. {
  8858. mBfIRBuilder->PopulateType(retTypeInstance);
  8859. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  8860. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  8861. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  8862. auto curThis = GetThis();
  8863. BfIRValue newFlags;
  8864. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8865. {
  8866. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  8867. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  8868. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  8869. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  8870. }
  8871. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  8872. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  8873. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  8874. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8875. mBfIRBuilder->CreateStore(srcVal, destAddr);
  8876. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8877. {
  8878. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  8879. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  8880. }
  8881. }
  8882. if (appendSizeValue)
  8883. {
  8884. EmitAppendAlign(appendAllocAlign);
  8885. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8886. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  8887. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8888. }
  8889. return retValue;
  8890. }
  8891. bool BfModule::IsOptimized()
  8892. {
  8893. if (mProject == NULL)
  8894. return false;
  8895. if (mIsComptimeModule)
  8896. return false;
  8897. int optLevel = GetModuleOptions().mOptLevel;
  8898. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  8899. }
  8900. bool BfModule::IsTargetingBeefBackend()
  8901. {
  8902. if (mProject == NULL)
  8903. return true;
  8904. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  8905. }
  8906. bool BfModule::WantsLifetimes()
  8907. {
  8908. if (mBfIRBuilder->mIgnoreWrites)
  8909. return false;
  8910. if ((mIsComptimeModule) && (mBfIRBuilder->HasDebugLocation()))
  8911. return true;
  8912. else if (mProject == NULL)
  8913. return false;
  8914. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  8915. }
  8916. bool BfModule::HasCompiledOutput()
  8917. {
  8918. return (!mSystem->mIsResolveOnly) && (mGeneratesCode) && (!mIsComptimeModule);
  8919. }
  8920. bool BfModule::HasExecutedOutput()
  8921. {
  8922. return ((!mSystem->mIsResolveOnly) && (mGeneratesCode)) || (mIsComptimeModule);
  8923. }
  8924. // We will skip the object access check for any occurrences of this value
  8925. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  8926. {
  8927. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  8928. return;
  8929. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  8930. return;
  8931. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  8932. return;
  8933. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  8934. }
  8935. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  8936. {
  8937. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  8938. return;
  8939. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  8940. return;
  8941. if (typedVal.mValue.IsConst())
  8942. {
  8943. int stringIdx = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  8944. if (stringIdx != -1)
  8945. return;
  8946. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  8947. if (constant->mTypeCode == BfTypeCode_NullPtr)
  8948. return;
  8949. if (constant->mConstType == BfConstType_BitCastNull)
  8950. return;
  8951. }
  8952. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  8953. auto typeOptions = GetTypeOptions();
  8954. if (typeOptions != NULL)
  8955. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  8956. if (!emitObjectAccessCheck)
  8957. return;
  8958. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  8959. {
  8960. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  8961. return;
  8962. }
  8963. if (typedVal.IsAddr())
  8964. typedVal = LoadValue(typedVal);
  8965. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  8966. }
  8967. void BfModule::EmitEnsureInstructionAt()
  8968. {
  8969. if (mBfIRBuilder->mIgnoreWrites)
  8970. return;
  8971. if (mIsComptimeModule)
  8972. {
  8973. // Always add
  8974. }
  8975. else if ((mProject == NULL) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  8976. return;
  8977. mBfIRBuilder->CreateEnsureInstructionAt();
  8978. }
  8979. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  8980. {
  8981. if (mBfIRBuilder->mIgnoreWrites)
  8982. return; // Nothing needed here
  8983. auto irb = mBfIRBuilder;
  8984. auto checkBB = irb->CreateBlock("as.check");
  8985. auto isNull = irb->CreateIsNull(targetValue.mValue);
  8986. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  8987. if (mIsComptimeModule)
  8988. {
  8989. AddBasicBlock(checkBB);
  8990. auto callResult = mBfIRBuilder->Comptime_DynamicCastCheck(targetValue.mValue, targetType->mTypeId, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8991. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult, GetDefaultValue(mContext->mBfObjectType));
  8992. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8993. return;
  8994. }
  8995. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8996. auto intPtrType = CreatePointerType(intType);
  8997. auto intPtrPtrType = CreatePointerType(intPtrType);
  8998. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  8999. auto int32PtrType = CreatePointerType(int32Type);
  9000. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  9001. if (mCompiler->mOptions.mAllowHotSwapping)
  9002. {
  9003. BfExprEvaluator exprEvaluator(this);
  9004. AddBasicBlock(checkBB);
  9005. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9006. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  9007. SizedArray<BfIRValue, 4> irArgs;
  9008. irArgs.push_back(objectParam);
  9009. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  9010. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  9011. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  9012. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9013. }
  9014. else
  9015. {
  9016. AddBasicBlock(checkBB);
  9017. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  9018. vDataPtr = irb->CreateLoad(vDataPtr);
  9019. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9020. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  9021. if (targetType->IsInterface())
  9022. {
  9023. auto targetTypeInst = targetType->ToTypeInstance();
  9024. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9025. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  9026. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  9027. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9028. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  9029. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  9030. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  9031. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  9032. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  9033. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9034. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  9035. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  9036. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9037. }
  9038. else
  9039. {
  9040. if (!targetType->IsTypeInstance())
  9041. targetType = GetWrappedStructType(targetType);
  9042. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9043. int inheritanceIdOfs = mSystem->mPtrSize;
  9044. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9045. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9046. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  9047. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  9048. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  9049. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  9050. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  9051. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9052. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  9053. fieldInst = &typeTypeInstance->mFieldInstances[10];
  9054. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  9055. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9056. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  9057. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  9058. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  9059. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9060. }
  9061. }
  9062. }
  9063. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  9064. {
  9065. if (mBfIRBuilder->mIgnoreWrites)
  9066. return;
  9067. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  9068. auto typeOptions = GetTypeOptions();
  9069. if (typeOptions != NULL)
  9070. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  9071. if (emitDynamicCastCheck)
  9072. {
  9073. int wantTypeId = 0;
  9074. if (!type->IsGenericParam())
  9075. wantTypeId = type->mTypeId;
  9076. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  9077. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  9078. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  9079. AddBasicBlock(failBlock);
  9080. if (mIsComptimeModule)
  9081. {
  9082. mBfIRBuilder->Comptime_Error(CeErrorKind_ObjectDynCheckFailed);
  9083. }
  9084. else
  9085. {
  9086. SizedArray<BfIRValue, 8> llvmArgs;
  9087. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9088. llvmArgs.push_back(bitAddr);
  9089. llvmArgs.push_back(GetConstValue32(wantTypeId));
  9090. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  9091. BF_ASSERT(objDynCheck);
  9092. if (objDynCheck)
  9093. {
  9094. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  9095. }
  9096. }
  9097. mBfIRBuilder->CreateBr(endBlock);
  9098. AddBasicBlock(endBlock);
  9099. }
  9100. }
  9101. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, BfCastFlags castFlags)
  9102. {
  9103. bool callDtor = (castFlags & BfCastFlags_NoBoxDtor) == 0;
  9104. bool wantConst = ((castFlags & BfCastFlags_WantsConst) != 0) && (typedVal.mValue.IsConst());
  9105. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9106. {
  9107. if (toType == mContext->mBfObjectType)
  9108. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9109. if (toType->IsBoxed())
  9110. {
  9111. BfBoxedType* boxedType = (BfBoxedType*)toType;
  9112. if (boxedType->mElementType->IsGenericParam())
  9113. {
  9114. if (typedVal.mType == boxedType->mElementType)
  9115. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9116. else
  9117. return BfTypedValue();
  9118. }
  9119. }
  9120. }
  9121. BP_ZONE("BoxValue");
  9122. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  9123. if (typedVal.mType->IsNullable())
  9124. {
  9125. typedVal = MakeAddressable(typedVal);
  9126. auto innerType = typedVal.mType->GetUnderlyingType();
  9127. if (!innerType->IsValueType())
  9128. {
  9129. if (!mIgnoreErrors)
  9130. Fail("Only value types can be boxed", srcNode);
  9131. return BfTypedValue();
  9132. }
  9133. auto boxedType = CreateBoxedType(innerType);
  9134. auto resultType = toType;
  9135. if (resultType == NULL)
  9136. resultType = boxedType;
  9137. if (mBfIRBuilder->mIgnoreWrites)
  9138. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  9139. auto prevBB = mBfIRBuilder->GetInsertBlock();
  9140. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  9141. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  9142. mBfIRBuilder->PopulateType(typedVal.mType);
  9143. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  9144. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  9145. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  9146. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9147. mBfIRBuilder->AddBlock(boxBB);
  9148. mBfIRBuilder->SetInsertPoint(boxBB);
  9149. BfScopeData newScope;
  9150. newScope.mOuterIsConditional = true;
  9151. mCurMethodState->AddScope(&newScope);
  9152. NewScopeState();
  9153. BfIRValue nullableValueAddr;
  9154. BfIRValue loadedVal;
  9155. if (innerType->IsValuelessType())
  9156. {
  9157. loadedVal = mBfIRBuilder->GetFakeVal();
  9158. }
  9159. else
  9160. {
  9161. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  9162. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  9163. }
  9164. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor ? BfCastFlags_None : BfCastFlags_NoBoxDtor);
  9165. RestoreScopeState();
  9166. if (!boxedVal)
  9167. return BfTypedValue();
  9168. mBfIRBuilder->CreateBr(endBB);
  9169. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  9170. mBfIRBuilder->AddBlock(endBB);
  9171. mBfIRBuilder->SetInsertPoint(endBB);
  9172. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  9173. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  9174. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  9175. return BfTypedValue(phi, resultType);
  9176. }
  9177. bool alreadyCheckedCast = false;
  9178. BfTypeInstance* toTypeInstance = NULL;
  9179. if (toType != NULL)
  9180. toTypeInstance = toType->ToTypeInstance();
  9181. bool isStructPtr = typedVal.mType->IsStructPtr();
  9182. if (fromStructTypeInstance == NULL)
  9183. {
  9184. auto primType = (BfPrimitiveType*)typedVal.mType;
  9185. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  9186. {
  9187. // Can always do IHashable
  9188. alreadyCheckedCast = true;
  9189. }
  9190. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  9191. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9192. else
  9193. {
  9194. auto checkStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9195. if (checkStructTypeInstance == toType->GetUnderlyingType())
  9196. fromStructTypeInstance = checkStructTypeInstance;
  9197. }
  9198. if (isStructPtr)
  9199. {
  9200. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9201. alreadyCheckedCast = true;
  9202. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  9203. }
  9204. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  9205. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9206. }
  9207. if (fromStructTypeInstance == NULL)
  9208. return BfTypedValue();
  9209. // Need to box it
  9210. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  9211. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9212. {
  9213. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9214. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  9215. auto boxedType = CreateBoxedType(typedVal.mType);
  9216. mBfIRBuilder->PopulateType(boxedType);
  9217. if (wantConst)
  9218. return BfTypedValue(mBfIRBuilder->CreateConstBox(typedVal.mValue, mBfIRBuilder->MapType(boxedType)), boxedType);
  9219. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9220. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  9221. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  9222. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  9223. if (boxedType->IsUnspecializedType())
  9224. {
  9225. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  9226. }
  9227. else
  9228. {
  9229. PopulateType(fromStructTypeInstance);
  9230. if (!fromStructTypeInstance->IsValuelessType())
  9231. {
  9232. typedVal = LoadValue(typedVal);
  9233. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  9234. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  9235. {
  9236. auto ptrType = CreatePointerType(typedVal.mType);
  9237. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  9238. }
  9239. if (typedVal.IsSplat())
  9240. {
  9241. AggregateSplatIntoAddr(typedVal, valPtr);
  9242. }
  9243. else
  9244. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr, typedVal.mType->mAlign);
  9245. }
  9246. }
  9247. if (toType == NULL)
  9248. {
  9249. return BfTypedValue(allocaInst, boxedType);
  9250. }
  9251. else
  9252. {
  9253. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  9254. return BfTypedValue(castedValue, toType);
  9255. }
  9256. }
  9257. return BfTypedValue();
  9258. }
  9259. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  9260. {
  9261. BfTypeInstance* checkTypeInst = typeInst;
  9262. while (checkTypeInst != NULL)
  9263. {
  9264. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  9265. {
  9266. if (checkProp->mName == propDef->mName)
  9267. {
  9268. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  9269. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  9270. {
  9271. propDef = checkProp;
  9272. typeInst = checkTypeInst;
  9273. return true;
  9274. }
  9275. }
  9276. }
  9277. checkTypeInst = checkTypeInst->mBaseType;
  9278. }
  9279. return false;
  9280. }
  9281. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  9282. {
  9283. if (!typeInstance->mResolvingVarField)
  9284. {
  9285. if (!typeInstance->DefineStateAllowsStaticMethods())
  9286. PopulateType(typeInstance, BfPopulateType_AllowStaticMethods);
  9287. }
  9288. else
  9289. {
  9290. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  9291. {
  9292. AssertErrorState();
  9293. return NULL;
  9294. }
  9295. }
  9296. if (assertName != NULL)
  9297. {
  9298. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9299. }
  9300. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9301. {
  9302. if (mCompiler->EnsureCeUnpaused(typeInstance))
  9303. {
  9304. BF_FATAL("OOB in GetRawMethodInstanceAtIdx");
  9305. }
  9306. return NULL;
  9307. }
  9308. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  9309. if (methodGroup.mDefault == NULL)
  9310. {
  9311. if (!mCompiler->mIsResolveOnly)
  9312. {
  9313. // Get it from the owning module so we don't create a reference prematurely...
  9314. auto declModule = typeInstance->mModule;
  9315. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  9316. {
  9317. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9318. if (!declModule->mIsScratchModule)
  9319. declModule->mOnDemandMethodCount++;
  9320. }
  9321. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  9322. (typeInstance->mTypeFailed) || (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted));
  9323. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  9324. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9325. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified);
  9326. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9327. }
  9328. else
  9329. {
  9330. auto declModule = typeInstance->mModule;
  9331. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass);
  9332. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9333. }
  9334. }
  9335. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9336. //TODO: Why did we have this adding methods to the work list? This should only happen if we actually attempt to USE the method, which should
  9337. // be from a call to the NON-raw version
  9338. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  9339. // {
  9340. // methodInstance->mIsReified = mIsReified;
  9341. // if (methodInstance->mMethodProcessRequest == NULL)
  9342. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  9343. // }
  9344. return methodInstance;
  9345. }
  9346. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  9347. {
  9348. if (methodDef->mIsLocalMethod)
  9349. {
  9350. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  9351. }
  9352. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx, NULL);
  9353. }
  9354. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  9355. {
  9356. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9357. while (typeInstance != NULL)
  9358. {
  9359. typeInstance->mTypeDef->PopulateMemberSets();
  9360. BfMemberSetEntry* entry = NULL;
  9361. BfMethodDef* methodDef = NULL;
  9362. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9363. methodDef = (BfMethodDef*)entry->mMemberDef;
  9364. while (methodDef != NULL)
  9365. {
  9366. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  9367. (methodDef->mGenericParams.size() == 0) &&
  9368. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9369. return GetRawMethodInstance(typeInstance, methodDef);
  9370. methodDef = methodDef->mNextWithSameName;
  9371. }
  9372. if (!checkBase)
  9373. break;
  9374. typeInstance = typeInstance->mBaseType;
  9375. }
  9376. return NULL;
  9377. }
  9378. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  9379. {
  9380. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9381. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  9382. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  9383. if (!useUnspecializedType)
  9384. return methodInstance;
  9385. if (!owner->IsGenericTypeInstance())
  9386. return methodInstance;
  9387. if ((owner->IsDelegateFromTypeRef()) ||
  9388. (owner->IsFunctionFromTypeRef()) ||
  9389. (owner->IsTuple()))
  9390. {
  9391. return methodInstance;
  9392. }
  9393. auto genericType = (BfTypeInstance*)owner;
  9394. if ((genericType->IsUnspecializedType()) && (!genericType->IsUnspecializedTypeVariation()))
  9395. return methodInstance;
  9396. if (methodInstance->mMethodDef->mIsLocalMethod)
  9397. return methodInstance;
  9398. if (methodInstance->mMethodDef->mDeclaringType->IsEmitted())
  9399. return methodInstance;
  9400. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef->GetDefinition());
  9401. if (unspecializedType == NULL)
  9402. {
  9403. AssertErrorState();
  9404. return methodInstance;
  9405. }
  9406. if (unspecializedType == NULL)
  9407. return methodInstance;
  9408. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  9409. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  9410. }
  9411. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  9412. {
  9413. int genericCount = 0;
  9414. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  9415. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  9416. {
  9417. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  9418. if (param->IsGenericParam())
  9419. genericCount++;
  9420. }
  9421. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  9422. genericCount++;
  9423. return genericCount;
  9424. }
  9425. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  9426. {
  9427. BF_ASSERT(!mIsScratchModule);
  9428. BF_ASSERT(mIsReified);
  9429. BfModule* mainModule = this;
  9430. if (mParentModule != NULL)
  9431. mainModule = mParentModule;
  9432. BfModule* specModule = NULL;
  9433. BfModule** specModulePtr = NULL;
  9434. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  9435. {
  9436. return *specModulePtr;
  9437. }
  9438. else
  9439. {
  9440. String specModuleName = mModuleName;
  9441. for (auto bfProject : projectList)
  9442. {
  9443. specModuleName += StrFormat("@%s", bfProject->mSafeName.c_str());
  9444. }
  9445. specModule = new BfModule(mContext, specModuleName);
  9446. specModule->mProject = mainModule->mProject;
  9447. specModule->mParentModule = mainModule;
  9448. specModule->mIsSpecializedMethodModuleRoot = true;
  9449. specModule->Init();
  9450. Array<BfProject*> projList;
  9451. for (auto project : projectList)
  9452. projList.Add(project);
  9453. mainModule->mSpecializedMethodModules[projList] = specModule;
  9454. }
  9455. return specModule;
  9456. }
  9457. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  9458. {
  9459. if (IsSkippingExtraResolveChecks())
  9460. return BfIRValue();
  9461. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  9462. {
  9463. //BF_ASSERT(!methodInstance->mIRFunction);
  9464. return BfIRValue();
  9465. }
  9466. auto methodDef = methodInstance->mMethodDef;
  9467. StringT<4096> methodName;
  9468. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  9469. if (isInlined != methodInstance->mAlwaysInline)
  9470. {
  9471. if (isInlined)
  9472. methodName += "__INLINE";
  9473. else
  9474. methodName += "__NOINLINE";
  9475. }
  9476. if (tryExisting)
  9477. {
  9478. auto func = mBfIRBuilder->GetFunction(methodName);
  9479. if (func)
  9480. return func;
  9481. }
  9482. auto intrinsic = GetIntrinsic(methodInstance);
  9483. if (intrinsic)
  9484. return intrinsic;
  9485. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  9486. {
  9487. return CreateDllImportGlobalVar(methodInstance, false);
  9488. }
  9489. BfIRType returnType;
  9490. SizedArray<BfIRType, 8> paramTypes;
  9491. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  9492. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  9493. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  9494. auto callingConv = GetIRCallingConvention(methodInstance);
  9495. if (callingConv != BfIRCallingConv_CDecl)
  9496. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  9497. SetupIRMethod(methodInstance, func, isInlined);
  9498. // auto srcModule = methodInstance->GetOwner()->GetModule();
  9499. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  9500. // {
  9501. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  9502. // {
  9503. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  9504. // }
  9505. // }
  9506. return func;
  9507. }
  9508. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  9509. {
  9510. if (assertName != NULL)
  9511. {
  9512. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9513. }
  9514. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9515. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9516. BfMethodDef* methodDef = NULL;
  9517. BfTypeInstance* foreignType = NULL;
  9518. if (methodInstance != NULL)
  9519. {
  9520. methodDef = methodInstance->mMethodDef;
  9521. if (methodInstance->mMethodInfoEx != NULL)
  9522. foreignType = methodInstance->mMethodInfoEx->mForeignType;
  9523. }
  9524. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  9525. {
  9526. // Can't use it, not reified
  9527. methodInstance = NULL;
  9528. }
  9529. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  9530. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  9531. {
  9532. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  9533. return BfModuleMethodInstance(methodInstance, func);
  9534. }
  9535. if (foreignType != NULL)
  9536. return GetMethodInstance(typeInstance, methodDef, BfTypeVector(), (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef), foreignType);
  9537. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  9538. }
  9539. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9540. {
  9541. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9542. while (typeInstance != NULL)
  9543. {
  9544. typeInstance->mTypeDef->PopulateMemberSets();
  9545. BfMemberSetEntry* entry = NULL;
  9546. BfMethodDef* methodDef = NULL;
  9547. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9548. methodDef = (BfMethodDef*)entry->mMemberDef;
  9549. while (methodDef != NULL)
  9550. {
  9551. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9552. (methodDef->mGenericParams.size() == 0) &&
  9553. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9554. {
  9555. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9556. if (moduleMethodInstance)
  9557. return moduleMethodInstance;
  9558. }
  9559. methodDef = methodDef->mNextWithSameName;
  9560. }
  9561. if (!checkBase)
  9562. break;
  9563. typeInstance = typeInstance->mBaseType;
  9564. }
  9565. return BfModuleMethodInstance();
  9566. }
  9567. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  9568. {
  9569. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9570. while (typeInstance != NULL)
  9571. {
  9572. typeInstance->mTypeDef->PopulateMemberSets();
  9573. BfMemberSetEntry* entry = NULL;
  9574. BfMethodDef* methodDef = NULL;
  9575. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9576. methodDef = (BfMethodDef*)entry->mMemberDef;
  9577. while (methodDef != NULL)
  9578. {
  9579. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9580. (methodDef->mGenericParams.size() == 0) &&
  9581. (paramTypes.size() == methodDef->mParams.size()))
  9582. {
  9583. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9584. if (moduleMethodInstance.mMethodInstance != NULL)
  9585. {
  9586. bool matches = true;
  9587. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  9588. {
  9589. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  9590. matches = false;
  9591. }
  9592. if (matches)
  9593. return moduleMethodInstance;
  9594. }
  9595. }
  9596. methodDef = methodDef->mNextWithSameName;
  9597. }
  9598. if (!checkBase)
  9599. break;
  9600. typeInstance = typeInstance->mBaseType;
  9601. }
  9602. return BfModuleMethodInstance();
  9603. }
  9604. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  9605. {
  9606. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  9607. PopulateType(internalType);
  9608. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  9609. if (!moduleMethodInstance)
  9610. {
  9611. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  9612. }
  9613. return moduleMethodInstance;
  9614. }
  9615. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  9616. {
  9617. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  9618. typeInstance->mOperatorInfo.Add(NULL);
  9619. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  9620. {
  9621. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  9622. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  9623. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  9624. BfTypeState typeState;
  9625. typeState.mType = typeInstance;
  9626. typeState.mCurTypeDef = operatorDef->mDeclaringType;
  9627. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  9628. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  9629. if (operatorDef->mReturnTypeRef != NULL)
  9630. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  9631. if (operatorDef->mParams.size() >= 1)
  9632. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  9633. if (operatorDef->mParams.size() >= 2)
  9634. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  9635. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  9636. }
  9637. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  9638. }
  9639. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  9640. {
  9641. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  9642. if (operatorInfo == NULL)
  9643. return NULL;
  9644. if (operatorInfo->mReturnType == NULL)
  9645. return NULL;
  9646. auto castFlags = BfCastFlags_IsConstraintCheck;
  9647. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9648. castFlags = (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator);
  9649. if (lhs)
  9650. {
  9651. if (operatorInfo->mLHSType == NULL)
  9652. return NULL;
  9653. if (!CanCast(lhs, operatorInfo->mLHSType, castFlags))
  9654. return NULL;
  9655. }
  9656. if (rhs)
  9657. {
  9658. if (operatorInfo->mRHSType == NULL)
  9659. return NULL;
  9660. if (!CanCast(rhs, operatorInfo->mRHSType, castFlags))
  9661. return NULL;
  9662. }
  9663. return operatorInfo->mReturnType;
  9664. }
  9665. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9666. {
  9667. while (typeInstance != NULL)
  9668. {
  9669. typeInstance->mTypeDef->PopulateMemberSets();
  9670. BfMemberSetEntry* entry = NULL;
  9671. BfMethodDef* methodDef = NULL;
  9672. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9673. methodDef = (BfMethodDef*)entry->mMemberDef;
  9674. while (methodDef != NULL)
  9675. {
  9676. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9677. (methodDef->mGenericParams.size() == 0) &&
  9678. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9679. {
  9680. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  9681. if (!methodInstanceGroup.IsImplemented())
  9682. return false;
  9683. if (methodInstanceGroup.mDefault == NULL)
  9684. return false;
  9685. return methodInstanceGroup.mDefault->mIsReified;
  9686. }
  9687. methodDef = methodDef->mNextWithSameName;
  9688. }
  9689. if (!checkBase)
  9690. break;
  9691. typeInstance = typeInstance->mBaseType;
  9692. }
  9693. return false;
  9694. }
  9695. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9696. {
  9697. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9698. while (typeInstance != NULL)
  9699. {
  9700. typeInstance->mTypeDef->PopulateMemberSets();
  9701. BfMemberSetEntry* entry = NULL;
  9702. BfMethodDef* methodDef = NULL;
  9703. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9704. methodDef = (BfMethodDef*)entry->mMemberDef;
  9705. while (methodDef != NULL)
  9706. {
  9707. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  9708. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9709. return true;
  9710. methodDef = methodDef->mNextWithSameName;
  9711. }
  9712. if (!checkBase)
  9713. break;
  9714. typeInstance = typeInstance->mBaseType;
  9715. }
  9716. return BfModuleMethodInstance();
  9717. }
  9718. String BfModule::FieldToString(BfFieldInstance* fieldInstance)
  9719. {
  9720. auto result = TypeToString(fieldInstance->mOwner);
  9721. result += ".";
  9722. auto fieldDef = fieldInstance->GetFieldDef();
  9723. if (fieldDef != NULL)
  9724. result += fieldDef->mName;
  9725. else
  9726. result += "???";
  9727. return result;
  9728. }
  9729. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* typeGenericArgs, BfTypeVector* methodGenericArgs)
  9730. {
  9731. auto methodDef = methodInst->mMethodDef;
  9732. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  9733. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9734. bool hasGenericArgs = (typeGenericArgs != NULL) || (methodGenericArgs != NULL);
  9735. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  9736. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9737. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  9738. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  9739. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9740. if (allowResolveGenericParamNames)
  9741. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9742. StringT<128> methodName;
  9743. auto _AddTypeName = [&](BfType* type)
  9744. {
  9745. auto typeNameFlags = BfTypeNameFlags_None;
  9746. if (allowResolveGenericParamNames)
  9747. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9748. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9749. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  9750. methodName += TypeToString(type, typeNameFlags);
  9751. };
  9752. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  9753. {
  9754. _AddTypeName(methodInst->mReturnType);
  9755. methodName += " ";
  9756. }
  9757. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  9758. {
  9759. methodName += TypeToString(type, typeNameFlags);
  9760. if (methodName == "$")
  9761. methodName = "";
  9762. else if (!methodName.IsEmpty())
  9763. methodName += ".";
  9764. }
  9765. String accessorString;
  9766. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  9767. if (methodInst->mMethodDef->mIsLocalMethod)
  9768. {
  9769. int atPos = (int)methodDefName.IndexOf('$');
  9770. methodDefName.RemoveToEnd(atPos);
  9771. methodDefName.Replace("@", ".");
  9772. }
  9773. else
  9774. {
  9775. int atPos = (int)methodDefName.IndexOf('$');
  9776. if (atPos != -1)
  9777. {
  9778. accessorString = methodDefName.Substring(0, atPos);
  9779. if ((accessorString == "get") || (accessorString == "set"))
  9780. {
  9781. methodDefName = methodDefName.Substring(atPos + 1);
  9782. }
  9783. else
  9784. accessorString = "";
  9785. }
  9786. }
  9787. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  9788. {
  9789. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9790. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9791. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9792. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  9793. methodName += ".";
  9794. }
  9795. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  9796. {
  9797. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9798. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9799. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9800. methodName += "[";
  9801. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  9802. methodName += "].";
  9803. }
  9804. if (methodDef->mMethodType == BfMethodType_Operator)
  9805. {
  9806. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  9807. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9808. {
  9809. // Don't add explicit/implicit part, since that's not available in GCC mangling
  9810. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  9811. {
  9812. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  9813. methodName += "explicit ";
  9814. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  9815. methodName += "explicit ";
  9816. }*/
  9817. methodName += "operator ";
  9818. if (methodInst->mReturnType != NULL)
  9819. methodName += TypeToString(methodInst->mReturnType);
  9820. }
  9821. else
  9822. {
  9823. methodName += "operator";
  9824. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  9825. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  9826. }
  9827. }
  9828. else if (methodDef->mMethodType == BfMethodType_Ctor)
  9829. {
  9830. if (methodDef->mIsStatic)
  9831. methodName += "__BfStaticCtor";
  9832. else
  9833. methodName += "this";
  9834. accessorString = "";
  9835. }
  9836. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  9837. {
  9838. auto propertyDecl = methodDef->GetPropertyDeclaration();
  9839. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  9840. {
  9841. methodName += "get indexer";
  9842. }
  9843. else
  9844. {
  9845. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  9846. propertyDecl->mNameNode->ToString(methodName);
  9847. methodName += " get accessor";
  9848. return methodName;
  9849. }
  9850. }
  9851. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  9852. {
  9853. auto propertyDecl = methodDef->GetPropertyDeclaration();
  9854. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  9855. {
  9856. methodName += "set indexer";
  9857. }
  9858. else
  9859. {
  9860. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  9861. propertyDecl->mNameNode->ToString(methodName);
  9862. methodName += " set accessor";
  9863. return methodName;
  9864. }
  9865. }
  9866. else
  9867. methodName += methodDefName;
  9868. if (methodDef->mMethodType == BfMethodType_Mixin)
  9869. methodName += "!";
  9870. BfTypeVector newMethodGenericArgs;
  9871. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9872. {
  9873. methodName += "<";
  9874. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  9875. {
  9876. if (i > 0)
  9877. methodName += ", ";
  9878. BfTypeNameFlags typeNameFlags = BfTypeNameFlag_ShortConst;
  9879. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  9880. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9881. if (allowResolveGenericParamNames)
  9882. typeNameFlags = (BfTypeNameFlags)(typeNameFlags | BfTypeNameFlag_ResolveGenericParamNames);
  9883. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  9884. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  9885. {
  9886. bool hasEmpty = false;
  9887. for (auto arg : *methodGenericArgs)
  9888. {
  9889. if (arg == NULL)
  9890. hasEmpty = true;
  9891. }
  9892. if (hasEmpty)
  9893. {
  9894. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  9895. {
  9896. auto arg = (*methodGenericArgs)[genericIdx];
  9897. if (arg != NULL)
  9898. newMethodGenericArgs.push_back(arg);
  9899. else
  9900. {
  9901. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  9902. if (genericParamInst->mTypeConstraint != NULL)
  9903. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  9904. else
  9905. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  9906. }
  9907. }
  9908. methodGenericArgs = &newMethodGenericArgs;
  9909. }
  9910. if (type->IsUnspecializedType())
  9911. type = ResolveGenericType(type, NULL, methodGenericArgs, mCurTypeInstance);
  9912. }
  9913. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  9914. {
  9915. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  9916. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  9917. methodName += TypeToString(type, typeNameFlags);
  9918. }
  9919. else
  9920. methodName += TypeToString(type, typeNameFlags);
  9921. }
  9922. methodName += ">";
  9923. }
  9924. if (accessorString.length() == 0)
  9925. {
  9926. int dispParamIdx = 0;
  9927. methodName += "(";
  9928. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  9929. {
  9930. int paramKind = methodInst->GetParamKind(paramIdx);
  9931. if ((paramKind == BfParamKind_ImplicitCapture) || (paramKind == BfParamKind_AppendIdx))
  9932. continue;
  9933. if (dispParamIdx > 0)
  9934. methodName += ", ";
  9935. if (paramKind == BfParamKind_Params)
  9936. methodName += "params ";
  9937. BfType* type = methodInst->GetParamType(paramIdx);
  9938. _AddTypeName(type);
  9939. methodName += " ";
  9940. methodName += methodInst->GetParamName(paramIdx);
  9941. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  9942. if ((paramInitializer != NULL) && ((methodNameFlags & BfMethodNameFlag_NoAst) == 0))
  9943. {
  9944. methodName += " = ";
  9945. methodName += paramInitializer->ToString();
  9946. }
  9947. dispParamIdx++;
  9948. }
  9949. methodName += ")";
  9950. }
  9951. if (accessorString.length() != 0)
  9952. {
  9953. methodName += " ";
  9954. methodName += accessorString;
  9955. }
  9956. if ((methodNameFlags & BfMethodNameFlag_IncludeMut) != 0)
  9957. {
  9958. if ((methodDef->mIsMutating) && (methodInst->GetOwner()->IsValueType()))
  9959. methodName += " mut";
  9960. }
  9961. return methodName;
  9962. }
  9963. void BfModule::pt(BfType* type)
  9964. {
  9965. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  9966. }
  9967. void BfModule::pm(BfMethodInstance* type)
  9968. {
  9969. OutputDebugStrF("%s\n", MethodToString(type).c_str());
  9970. }
  9971. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  9972. {
  9973. if ((flagsLeft & checkFlag) == 0)
  9974. return;
  9975. if (!str.empty())
  9976. {
  9977. if (flagsLeft == checkFlag)
  9978. {
  9979. if ((int)str.IndexOf(',') != -1)
  9980. str += ", and ";
  9981. else
  9982. str += " and ";
  9983. }
  9984. else
  9985. str += ", ";
  9986. }
  9987. str += addString;
  9988. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  9989. }
  9990. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  9991. {
  9992. String resultStr;
  9993. auto flagsLeft = attrTarget;
  9994. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  9995. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  9996. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  9997. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  9998. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  9999. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  10000. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  10001. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  10002. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  10003. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  10004. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  10005. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  10006. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  10007. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  10008. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  10009. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  10010. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  10011. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  10012. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  10013. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  10014. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  10015. if (resultStr.IsEmpty())
  10016. return "<nothing>";
  10017. return resultStr;
  10018. }
  10019. BfIRType BfModule::CurrentAddToConstHolder(BfIRType irType)
  10020. {
  10021. if (irType.mKind == BfIRTypeData::TypeKind_SizedArray)
  10022. {
  10023. auto sizedArrayType = (BfConstantSizedArrayType*)mBfIRBuilder->GetConstantById(irType.mId);
  10024. return mCurTypeInstance->GetOrCreateConstHolder()->GetSizedArrayType(CurrentAddToConstHolder(sizedArrayType->mType), (int)sizedArrayType->mLength);
  10025. }
  10026. return irType;
  10027. }
  10028. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  10029. {
  10030. auto constant = mBfIRBuilder->GetConstant(irVal);
  10031. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  10032. if (stringPoolIdx != -1)
  10033. {
  10034. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  10035. return;
  10036. }
  10037. if (constant->mConstType == BfConstType_Agg)
  10038. {
  10039. auto constArray = (BfConstantAgg*)constant;
  10040. SizedArray<BfIRValue, 8> newVals;
  10041. for (auto val : constArray->mValues)
  10042. {
  10043. auto newVal = val;
  10044. CurrentAddToConstHolder(newVal);
  10045. newVals.push_back(newVal);
  10046. }
  10047. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstAgg(CurrentAddToConstHolder(constArray->mType), newVals);
  10048. return;
  10049. }
  10050. auto origConst = irVal;
  10051. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10052. {
  10053. auto bitcast = (BfConstantBitCast*)constant;
  10054. BfIRValue newVal;
  10055. if (bitcast->mTarget)
  10056. {
  10057. newVal = BfIRValue(BfIRValueFlags_Const, bitcast->mTarget);
  10058. CurrentAddToConstHolder(newVal);
  10059. }
  10060. else
  10061. newVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstNull();
  10062. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstBitCast(newVal, CurrentAddToConstHolder(bitcast->mToType));
  10063. return;
  10064. }
  10065. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  10066. }
  10067. void BfModule::ClearConstData()
  10068. {
  10069. mBfIRBuilder->ClearConstData();
  10070. mStringObjectPool.Clear();
  10071. mStringCharPtrPool.Clear();
  10072. mStringPoolRefs.Clear();
  10073. mUnreifiedStringPoolRefs.Clear();
  10074. mStaticFieldRefs.Clear();
  10075. }
  10076. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  10077. {
  10078. switch (constant->mTypeCode)
  10079. {
  10080. case BfTypeCode_StringId:
  10081. case BfTypeCode_Boolean:
  10082. case BfTypeCode_Int8:
  10083. case BfTypeCode_UInt8:
  10084. case BfTypeCode_Int16:
  10085. case BfTypeCode_UInt16:
  10086. case BfTypeCode_Int32:
  10087. case BfTypeCode_UInt32:
  10088. case BfTypeCode_Int64:
  10089. case BfTypeCode_UInt64:
  10090. case BfTypeCode_IntPtr:
  10091. case BfTypeCode_UIntPtr:
  10092. case BfTypeCode_IntUnknown:
  10093. case BfTypeCode_UIntUnknown:
  10094. case BfTypeCode_Char8:
  10095. case BfTypeCode_Char16:
  10096. case BfTypeCode_Char32:
  10097. case BfTypeCode_Float:
  10098. case BfTypeCode_Double:
  10099. {
  10100. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10101. BfTypedValue typedValue;
  10102. bool allowUnactualized = mBfIRBuilder->mIgnoreWrites;
  10103. if (constant->mTypeCode == BfTypeCode_StringId)
  10104. {
  10105. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10106. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10107. {
  10108. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType, allowUnactualized), wantType);
  10109. return typedValue;
  10110. }
  10111. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  10112. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType, allowUnactualized), stringType);
  10113. }
  10114. if (!typedValue)
  10115. {
  10116. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10117. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  10118. }
  10119. if (typedValue.mType == wantType)
  10120. return typedValue;
  10121. if (wantType->IsTypedPrimitive())
  10122. {
  10123. if (typedValue.mType == wantType->GetUnderlyingType())
  10124. {
  10125. typedValue.mType = wantType;
  10126. return typedValue;
  10127. }
  10128. }
  10129. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  10130. if (!castedTypedValue)
  10131. return BfTypedValue();
  10132. return castedTypedValue;
  10133. }
  10134. break;
  10135. default: break;
  10136. }
  10137. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  10138. BF_ASSERT(irValue);
  10139. if (!irValue)
  10140. return BfTypedValue();
  10141. if (constant->mConstType == BfConstType_GlobalVar)
  10142. {
  10143. mBfIRBuilder->PopulateType(wantType);
  10144. auto result = BfTypedValue(irValue, wantType, true);
  10145. if (!wantType->IsComposite())
  10146. result = LoadValue(result);
  10147. return result;
  10148. }
  10149. return BfTypedValue(irValue, wantType, false);
  10150. }
  10151. bool BfModule::HasUnactializedConstant(BfConstant* constant, BfIRConstHolder* constHolder)
  10152. {
  10153. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  10154. return true;
  10155. if (constant->mTypeCode == BfTypeCode_StringId)
  10156. return true;
  10157. if (constant->mConstType == BfConstType_Agg)
  10158. {
  10159. auto constArray = (BfConstantAgg*)constant;
  10160. for (auto val : constArray->mValues)
  10161. {
  10162. if (HasUnactializedConstant(constHolder->GetConstant(val), constHolder))
  10163. return true;
  10164. }
  10165. }
  10166. return false;
  10167. }
  10168. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType, bool allowUnactualized)
  10169. {
  10170. if (constant->mTypeCode == BfTypeCode_NullPtr)
  10171. {
  10172. if ((wantType == NULL) && (constant->mIRType.mKind == BfIRTypeData::TypeKind_TypeId))
  10173. wantType = mContext->mTypes[constant->mIRType.mId];
  10174. if (wantType == NULL)
  10175. return mBfIRBuilder->CreateConstNull();
  10176. return GetDefaultValue(wantType);
  10177. }
  10178. if (constant->mTypeCode == BfTypeCode_StringId)
  10179. {
  10180. if (!allowUnactualized)
  10181. {
  10182. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10183. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10184. {
  10185. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  10186. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  10187. if (wantType->IsPointer())
  10188. return GetStringCharPtr(stringObjConst, true);
  10189. return stringObjConst;
  10190. }
  10191. }
  10192. }
  10193. if (constant->mConstType == Beefy::BfConstType_TypeOf)
  10194. {
  10195. auto constTypeOf = (BfTypeOf_Const*)constant;
  10196. if (mCurTypeInstance != NULL)
  10197. AddDependency(constTypeOf->mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10198. return CreateTypeDataRef(constTypeOf->mType);
  10199. }
  10200. if (constant->mConstType == BfConstType_PtrToInt)
  10201. {
  10202. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  10203. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10204. return mBfIRBuilder->CreatePtrToInt(ConstantToCurrent(fromTarget, constHolder, NULL), fromPtrToInt->mToTypeCode);
  10205. }
  10206. if (constant->mConstType == BfConstType_IntToPtr)
  10207. {
  10208. auto fromPtrToInt = (BfConstantIntToPtr*)constant;
  10209. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10210. BfIRType toIRType = fromPtrToInt->mToType;
  10211. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10212. {
  10213. auto toType = mContext->mTypes[toIRType.mId];
  10214. toIRType = mBfIRBuilder->MapType(toType);
  10215. }
  10216. return mBfIRBuilder->CreateIntToPtr(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10217. }
  10218. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10219. {
  10220. auto bitcast = (BfConstantBitCast*)constant;
  10221. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  10222. BfIRType toIRType = bitcast->mToType;
  10223. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10224. {
  10225. auto toType = mContext->mTypes[toIRType.mId];
  10226. toIRType = mBfIRBuilder->MapType(toType);
  10227. }
  10228. return mBfIRBuilder->CreateBitCast(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10229. }
  10230. if (constant->mConstType == BfConstType_Agg)
  10231. {
  10232. auto constArray = (BfConstantAgg*)constant;
  10233. if ((wantType == NULL) && (constArray->mType.mKind == BfIRTypeData::TypeKind_TypeId))
  10234. wantType = mContext->mTypes[constArray->mType.mId];
  10235. if (wantType->IsArray())
  10236. wantType = CreateSizedArrayType(wantType->GetUnderlyingType(), (int)constArray->mValues.mSize);
  10237. bool handleAsArray = false;
  10238. SizedArray<BfIRValue, 8> newVals;
  10239. if (wantType->IsSizedArray())
  10240. {
  10241. handleAsArray = true;
  10242. }
  10243. else if (wantType->IsInstanceOf(mCompiler->mSpanTypeDef))
  10244. {
  10245. auto valueType = ResolveTypeDef(mCompiler->mValueTypeTypeDef);
  10246. handleAsArray = true;
  10247. if (!constArray->mValues.IsEmpty())
  10248. {
  10249. auto firstConstant = constHolder->GetConstant(constArray->mValues[0]);
  10250. if ((firstConstant->mConstType == BfConstType_AggZero) && (firstConstant->mIRType.mKind == BfIRType::TypeKind_TypeId) &&
  10251. (firstConstant->mIRType.mId == valueType->mTypeId))
  10252. handleAsArray = false;
  10253. if (firstConstant->mConstType == BfConstType_Agg)
  10254. {
  10255. auto firstConstArray = (BfConstantAgg*)firstConstant;
  10256. if ((firstConstArray->mType.mKind == BfIRType::TypeKind_TypeId) &&
  10257. (firstConstArray->mType.mId == valueType->mTypeId))
  10258. handleAsArray = false;
  10259. }
  10260. }
  10261. }
  10262. if (handleAsArray)
  10263. {
  10264. auto elementType = wantType->GetUnderlyingType();
  10265. for (auto val : constArray->mValues)
  10266. {
  10267. newVals.Add(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  10268. }
  10269. }
  10270. else
  10271. {
  10272. auto wantTypeInst = wantType->ToTypeInstance();
  10273. if (wantTypeInst->mBaseType != NULL)
  10274. {
  10275. auto baseVal = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[0]), constHolder, wantTypeInst->mBaseType);
  10276. newVals.Add(baseVal);
  10277. }
  10278. if (wantType->IsUnion())
  10279. {
  10280. auto innerType = wantType->ToTypeInstance()->GetUnionInnerType();
  10281. if (!innerType->IsValuelessType())
  10282. {
  10283. auto val = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[1]), constHolder, innerType);
  10284. newVals.Add(val);
  10285. }
  10286. }
  10287. if ((!wantType->IsUnion()) || (wantType->IsPayloadEnum()))
  10288. {
  10289. for (auto& fieldInstance : wantTypeInst->mFieldInstances)
  10290. {
  10291. if (fieldInstance.mDataIdx < 0)
  10292. continue;
  10293. auto val = constArray->mValues[fieldInstance.mDataIdx];
  10294. BfIRValue memberVal = ConstantToCurrent(constHolder->GetConstant(val), constHolder, fieldInstance.mResolvedType);
  10295. if (fieldInstance.mDataIdx == newVals.mSize)
  10296. newVals.Add(memberVal);
  10297. else
  10298. {
  10299. while (fieldInstance.mDataIdx >= newVals.mSize)
  10300. newVals.Add(BfIRValue());
  10301. newVals[fieldInstance.mDataIdx] = memberVal;
  10302. }
  10303. }
  10304. }
  10305. for (auto& val : newVals)
  10306. {
  10307. if (!val)
  10308. val = mBfIRBuilder->CreateConstArrayZero(0);
  10309. }
  10310. }
  10311. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(wantType, BfIRPopulateType_Identity), newVals);
  10312. }
  10313. return mBfIRBuilder->CreateConst(constant, constHolder);
  10314. }
  10315. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  10316. {
  10317. if (attrTarget == BfAttributeTargets_SkipValidate)
  10318. return;
  10319. for (auto& customAttribute : customAttributes->mAttributes)
  10320. {
  10321. if (!customAttribute.mAwaitingValidation)
  10322. continue;
  10323. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  10324. {
  10325. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  10326. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  10327. }
  10328. customAttribute.mAwaitingValidation = false;
  10329. }
  10330. }
  10331. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10332. {
  10333. bool allowNonConstArgs = (flags & BfGetCustomAttributesFlags_AllowNonConstArgs) != 0;
  10334. bool keepConstsInModule = (flags & BfGetCustomAttributesFlags_KeepConstsInModule) != 0;
  10335. if (!mCompiler->mHasRequiredTypes)
  10336. return;
  10337. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  10338. {
  10339. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  10340. sourceClassifier->VisitChild(attributesDirective);
  10341. }
  10342. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  10343. if (mCompiler->IsAutocomplete())
  10344. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  10345. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  10346. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  10347. BfTypeDef* activeTypeDef = GetActiveTypeDef();
  10348. BfAutoComplete* autoComplete = NULL;
  10349. if (mCompiler->mResolvePassData != NULL)
  10350. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  10351. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  10352. {
  10353. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  10354. {
  10355. if (captureInfo == NULL)
  10356. {
  10357. Fail("Capture specifiers can only be used in lambda allocations", tokenNode);
  10358. continue;
  10359. }
  10360. BfCaptureInfo::Entry captureEntry;
  10361. captureEntry.mCaptureType = (tokenNode->mToken == BfToken_Ampersand) ? BfCaptureType_Reference : BfCaptureType_Copy;
  10362. if (!attributesDirective->mArguments.IsEmpty())
  10363. {
  10364. captureEntry.mNameNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]);
  10365. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  10366. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  10367. }
  10368. captureInfo->mCaptures.Add(captureEntry);
  10369. continue;
  10370. }
  10371. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  10372. BfCustomAttribute customAttribute;
  10373. customAttribute.mAwaitingValidation = true;
  10374. customAttribute.mDeclaringType = activeTypeDef;
  10375. customAttribute.mRef = attributesDirective;
  10376. if (attributesDirective->mAttrOpenToken != NULL)
  10377. targetOverride = (BfAttributeTargets)0;
  10378. if (attributesDirective->mAttributeTypeRef == NULL)
  10379. {
  10380. AssertErrorState();
  10381. continue;
  10382. }
  10383. BfType* attrType;
  10384. if (mContext->mCurTypeState != NULL)
  10385. {
  10386. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10387. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10388. }
  10389. else
  10390. {
  10391. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10392. }
  10393. BfTypeDef* attrTypeDef = NULL;
  10394. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  10395. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  10396. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10397. {
  10398. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  10399. if (attrTypeDef != NULL)
  10400. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  10401. }
  10402. bool isBypassedAttr = false;
  10403. if (attrTypeDef != NULL)
  10404. {
  10405. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  10406. // We solve it by having a 'bypass' for known attributes that Object depends on
  10407. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  10408. {
  10409. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  10410. {
  10411. for (auto methodDef : attrTypeDef->mMethods)
  10412. {
  10413. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  10414. {
  10415. customAttribute.mType = attrType->ToTypeInstance();
  10416. customAttribute.mCtor = methodDef;
  10417. isBypassedAttr = true;
  10418. break;
  10419. }
  10420. }
  10421. }
  10422. }
  10423. if (isBypassedAttr)
  10424. {
  10425. customAttribute.mAwaitingValidation = false;
  10426. customAttributes->mAttributes.push_back(customAttribute);
  10427. continue;
  10428. }
  10429. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInst(mContext->mUnreifiedModule->mCurTypeInstance, mCurTypeInstance);
  10430. SetAndRestoreValue<BfMethodInstance*> prevCurMethodInst(mContext->mUnreifiedModule->mCurMethodInstance, mCurMethodInstance);
  10431. if (mContext->mCurTypeState != NULL)
  10432. {
  10433. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10434. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10435. }
  10436. else
  10437. {
  10438. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10439. }
  10440. }
  10441. BfTypeInstance* attrTypeInst = NULL;
  10442. if (attrType == NULL)
  10443. continue;
  10444. attrTypeInst = attrType->ToTypeInstance();
  10445. if ((attrTypeInst != NULL) && (attrTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting))
  10446. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  10447. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  10448. {
  10449. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  10450. continue;
  10451. }
  10452. if ((mIsReified) && (attrTypeInst->mAttributeData != NULL) && ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_ReflectAttribute) != 0))
  10453. {
  10454. // Reify attribute
  10455. PopulateType(attrTypeInst);
  10456. }
  10457. if (mCurTypeInstance != NULL)
  10458. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10459. customAttribute.mType = attrTypeInst;
  10460. bool allocatedMethodState = NULL;
  10461. defer(
  10462. {
  10463. if (allocatedMethodState)
  10464. {
  10465. delete mCurMethodState;
  10466. mCurMethodState = NULL;
  10467. }
  10468. });
  10469. if (mCurMethodState == NULL)
  10470. {
  10471. allocatedMethodState = true;
  10472. mCurMethodState = new BfMethodState();
  10473. mCurMethodState->mTempKind = BfMethodState::TempKind_Static;
  10474. }
  10475. BfConstResolver constResolver(this);
  10476. if (allowNonConstArgs)
  10477. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  10478. bool inPropSet = false;
  10479. SizedArray<BfResolvedArg, 2> argValues;
  10480. for (BfExpression* arg : attributesDirective->mArguments)
  10481. {
  10482. if (arg == NULL)
  10483. {
  10484. continue;
  10485. }
  10486. if (autoComplete != NULL)
  10487. autoComplete->mShowAttributeProperties = attrTypeInst;
  10488. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  10489. {
  10490. inPropSet = true;
  10491. if (autoComplete != NULL)
  10492. autoComplete->CheckNode(assignExpr->mLeft, true);
  10493. String findName = assignExpr->mLeft->ToString();
  10494. BfPropertyDef* bestProp = NULL;
  10495. BfTypeInstance* bestPropTypeInst = NULL;
  10496. BfFieldDef* bestField = NULL;
  10497. BfTypeInstance* bestFieldTypeInst = NULL;
  10498. auto checkTypeInst = attrTypeInst;
  10499. while (checkTypeInst != NULL)
  10500. {
  10501. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  10502. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  10503. {
  10504. if (prop->mName == findName)
  10505. {
  10506. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  10507. {
  10508. bestProp = prop;
  10509. bestPropTypeInst = checkTypeInst;
  10510. }
  10511. }
  10512. }
  10513. for (auto field : checkTypeInst->mTypeDef->mFields)
  10514. {
  10515. if (field->mName == findName)
  10516. {
  10517. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  10518. {
  10519. bestField = field;
  10520. bestFieldTypeInst = checkTypeInst;
  10521. }
  10522. }
  10523. }
  10524. if ((bestProp != NULL) || (bestField != NULL))
  10525. break;
  10526. checkTypeInst = checkTypeInst->mBaseType;
  10527. }
  10528. bool handledExpr = false;
  10529. if (bestField != NULL)
  10530. {
  10531. handledExpr = true;
  10532. if (mCompiler->mResolvePassData != NULL)
  10533. {
  10534. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  10535. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10536. {
  10537. autoComplete->mDefField = bestField;
  10538. autoComplete->mDefType = attrTypeDef;
  10539. }
  10540. }
  10541. if (bestField->mProtection != BfProtection_Public)
  10542. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10543. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10544. BfCustomAttributeSetField setField;
  10545. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  10546. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  10547. if (assignExpr->mRight != NULL)
  10548. {
  10549. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType, BfConstResolveFlag_NoActualizeValues);
  10550. if (result)
  10551. {
  10552. if (!keepConstsInModule)
  10553. CurrentAddToConstHolder(result.mValue);
  10554. setField.mParam = result;
  10555. customAttribute.mSetField.push_back(setField);
  10556. }
  10557. }
  10558. }
  10559. else if (bestProp == NULL)
  10560. {
  10561. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  10562. }
  10563. else
  10564. {
  10565. BfMethodDef* setMethod = NULL;
  10566. for (auto methodDef : bestProp->mMethods)
  10567. {
  10568. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10569. {
  10570. setMethod = methodDef;
  10571. break;
  10572. }
  10573. }
  10574. if (setMethod == NULL)
  10575. {
  10576. Fail("Property has no setter", assignExpr->mLeft);
  10577. }
  10578. else
  10579. {
  10580. if (mCompiler->mResolvePassData != NULL)
  10581. {
  10582. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  10583. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10584. {
  10585. autoComplete->mDefProp = bestProp;
  10586. autoComplete->mDefType = attrTypeDef;
  10587. }
  10588. }
  10589. handledExpr = true;
  10590. if (bestProp->mProtection != BfProtection_Public)
  10591. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10592. BfResolvedArg resolvedArg;
  10593. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10594. BfCustomAttributeSetProperty setProperty;
  10595. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  10596. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  10597. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  10598. if (methodInstance.mMethodInstance != NULL)
  10599. {
  10600. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  10601. if (assignExpr->mRight != NULL)
  10602. {
  10603. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType, BfConstResolveFlag_NoActualizeValues);
  10604. if ((result) && (!result.mType->IsVar()))
  10605. {
  10606. if (!result.mValue.IsConst())
  10607. result = GetDefaultTypedValue(result.mType);
  10608. BF_ASSERT(result.mType == propType);
  10609. if (!keepConstsInModule)
  10610. CurrentAddToConstHolder(result.mValue);
  10611. setProperty.mParam = result;
  10612. customAttribute.mSetProperties.push_back(setProperty);
  10613. }
  10614. }
  10615. }
  10616. }
  10617. }
  10618. if ((!handledExpr) && (assignExpr->mRight != NULL))
  10619. constResolver.Resolve(assignExpr->mRight, NULL, BfConstResolveFlag_NoActualizeValues);
  10620. }
  10621. else
  10622. {
  10623. if (inPropSet)
  10624. {
  10625. Fail("Named attribute argument expected", arg); // CS1016
  10626. }
  10627. BfDeferEvalChecker deferEvalChecker;
  10628. arg->Accept(&deferEvalChecker);
  10629. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  10630. BfResolvedArg resolvedArg;
  10631. resolvedArg.mExpression = arg;
  10632. if (deferParamEval)
  10633. {
  10634. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  10635. }
  10636. else
  10637. resolvedArg.mTypedValue = constResolver.Resolve(arg, NULL, BfConstResolveFlag_NoActualizeValues);
  10638. if (!inPropSet)
  10639. {
  10640. argValues.push_back(resolvedArg);
  10641. }
  10642. }
  10643. if (autoComplete != NULL)
  10644. autoComplete->mShowAttributeProperties = NULL;
  10645. }
  10646. auto wasCapturingMethodInfo = false;
  10647. if (autoComplete != NULL)
  10648. {
  10649. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  10650. if (attributesDirective->mCtorOpenParen != NULL)
  10651. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  10652. }
  10653. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, BfMethodGenericArguments());
  10654. methodMatcher.mBfEvalExprFlags = constResolver.mBfEvalExprFlags;
  10655. attrTypeDef = attrTypeInst->mTypeDef;
  10656. bool success = true;
  10657. bool isFailurePass = false;
  10658. for (int pass = 0; pass < 2; pass++)
  10659. {
  10660. bool isFailurePass = pass == 1;
  10661. for (auto checkMethod : attrTypeDef->mMethods)
  10662. {
  10663. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  10664. continue; // Don't match private default ctor if there's a user-defined one
  10665. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  10666. continue;
  10667. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  10668. continue;
  10669. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  10670. }
  10671. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  10672. break;
  10673. }
  10674. if (autoComplete != NULL)
  10675. {
  10676. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  10677. {
  10678. autoComplete->mIsCapturingMethodMatchInfo = true;
  10679. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  10680. }
  10681. else
  10682. autoComplete->mIsCapturingMethodMatchInfo = false;
  10683. }
  10684. if (methodMatcher.mBestMethodDef == NULL)
  10685. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  10686. if (methodMatcher.mBestMethodDef == NULL)
  10687. {
  10688. AssertErrorState();
  10689. continue;
  10690. }
  10691. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  10692. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  10693. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  10694. {
  10695. Fail("Custom attribute circular reference", attributesDirective);
  10696. }
  10697. if (mCurTypeInstance != NULL)
  10698. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10699. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  10700. success = false;
  10701. for (auto& arg : argValues)
  10702. {
  10703. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  10704. {
  10705. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  10706. constResolver.Resolve(expr, NULL, BfConstResolveFlag_NoActualizeValues);
  10707. }
  10708. }
  10709. // Move all those to the constHolder
  10710. if (!keepConstsInModule)
  10711. {
  10712. for (auto& ctorArg : customAttribute.mCtorArgs)
  10713. {
  10714. if (ctorArg.IsConst())
  10715. CurrentAddToConstHolder(ctorArg);
  10716. }
  10717. }
  10718. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  10719. {
  10720. targetOverride = BfAttributeTargets_ReturnValue;
  10721. if (attrTarget != BfAttributeTargets_Method)
  10722. {
  10723. Fail(StrFormat("'%s' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are '%s'. All attributes in this block will be ignored.",
  10724. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  10725. success = false;
  10726. }
  10727. }
  10728. if ((success) && (targetOverride != (BfAttributeTargets)0))
  10729. {
  10730. if ((mCurMethodInstance != NULL) && (targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  10731. {
  10732. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  10733. if (methodInfoEx->mMethodCustomAttributes == NULL)
  10734. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  10735. if (success)
  10736. {
  10737. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  10738. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  10739. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  10740. }
  10741. }
  10742. // Mark as failed since we don't actually want to add this to the custom attributes set
  10743. success = false;
  10744. }
  10745. if (success)
  10746. {
  10747. if ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_DisallowAllowMultiple) != 0)
  10748. {
  10749. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  10750. {
  10751. if (prevCustomAttribute.mType == attrTypeInst)
  10752. {
  10753. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToCleanAttributeString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  10754. }
  10755. }
  10756. }
  10757. }
  10758. if (success)
  10759. {
  10760. customAttributes->mAttributes.push_back(customAttribute);
  10761. }
  10762. }
  10763. ValidateCustomAttributes(customAttributes, attrTarget);
  10764. }
  10765. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10766. {
  10767. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  10768. GetCustomAttributes(customAttributes, attributesDirective, attrType, flags, captureInfo);
  10769. return customAttributes;
  10770. }
  10771. BfCustomAttributes* BfModule::GetCustomAttributes(BfTypeDef* typeDef)
  10772. {
  10773. BF_ASSERT(mCompiler->IsAutocomplete());
  10774. BfAttributeTargets attrTarget;
  10775. if (typeDef->mIsDelegate)
  10776. attrTarget = BfAttributeTargets_Delegate;
  10777. else if (typeDef->mIsFunction)
  10778. attrTarget = BfAttributeTargets_Function;
  10779. else if (typeDef->mTypeCode == BfTypeCode_Enum)
  10780. attrTarget = BfAttributeTargets_Enum;
  10781. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  10782. attrTarget = BfAttributeTargets_Interface;
  10783. else if (typeDef->mTypeCode == BfTypeCode_Struct)
  10784. attrTarget = BfAttributeTargets_Struct;
  10785. else
  10786. attrTarget = BfAttributeTargets_Class;
  10787. return GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  10788. }
  10789. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  10790. {
  10791. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  10792. Warn(0, "Unused attributes", attributeState->mSrc);
  10793. }
  10794. void BfModule::ProcessTypeInstCustomAttributes(int& packing, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  10795. {
  10796. if (mCurTypeInstance->mTypeDef->mIsAlwaysInclude)
  10797. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  10798. if (mCurTypeInstance->mCustomAttributes != NULL)
  10799. {
  10800. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  10801. {
  10802. String typeName = TypeToString(customAttribute.mType);
  10803. if (typeName == "System.PackedAttribute")
  10804. {
  10805. packing = 1;
  10806. if (customAttribute.mCtorArgs.size() >= 1)
  10807. {
  10808. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10809. int checkPacking = alignConstant->mInt32;
  10810. if (((checkPacking & (checkPacking - 1)) == 0) && (packing > 0) && (packing < 256))
  10811. packing = checkPacking;
  10812. else
  10813. Fail("Packing must be a power of 2", customAttribute.GetRefNode());
  10814. }
  10815. }
  10816. else if (typeName == "System.UnionAttribute")
  10817. {
  10818. isUnion = true;
  10819. }
  10820. else if (typeName == "System.CReprAttribute")
  10821. {
  10822. isCRepr = true;
  10823. isOrdered = true;
  10824. }
  10825. else if (typeName == "System.OrderedAttribute")
  10826. {
  10827. isOrdered = true;
  10828. }
  10829. else if (typeName == "System.AlwaysIncludeAttribute")
  10830. {
  10831. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  10832. for (auto setProp : customAttribute.mSetProperties)
  10833. {
  10834. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  10835. if (propertyDef->mName == "AssumeInstantiated")
  10836. {
  10837. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10838. if ((constant != NULL) && (constant->mBool))
  10839. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_AssumeInstantiated);
  10840. }
  10841. else if (propertyDef->mName == "IncludeAllMethods")
  10842. {
  10843. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10844. if ((constant != NULL) && (constant->mBool))
  10845. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_IncludeAllMethods);
  10846. }
  10847. }
  10848. }
  10849. else if (typeName == "System.AlignAttribute")
  10850. {
  10851. if (customAttribute.mCtorArgs.size() >= 1)
  10852. {
  10853. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10854. int checkAlign = alignConstant->mInt32;
  10855. if ((checkAlign & (checkAlign - 1)) == 0)
  10856. alignOverride = checkAlign;
  10857. else
  10858. Fail("Alignment must be a power of 2", customAttribute.GetRefNode());
  10859. }
  10860. }
  10861. else if (typeName == "System.UnderlyingArrayAttribute")
  10862. {
  10863. if (customAttribute.mCtorArgs.size() >= 2)
  10864. {
  10865. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10866. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  10867. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  10868. {
  10869. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  10870. underlyingArraySize = sizeConstant->mInt32;
  10871. }
  10872. }
  10873. }
  10874. if (customAttribute.mType->mAttributeData == NULL)
  10875. PopulateType(customAttribute.mType);
  10876. BF_ASSERT(customAttribute.mType->mAttributeData != NULL);
  10877. if ((customAttribute.mType->mAttributeData != NULL) && ((customAttribute.mType->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0))
  10878. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | customAttribute.mType->mAttributeData->mAlwaysIncludeUser);
  10879. }
  10880. }
  10881. }
  10882. // Checking to see if we're an attribute or not
  10883. void BfModule::ProcessCustomAttributeData()
  10884. {
  10885. if (mCurTypeInstance->mAttributeData != NULL)
  10886. return;
  10887. bool isAttribute = false;
  10888. auto checkTypeInst = mCurTypeInstance->mBaseType;
  10889. while (checkTypeInst != NULL)
  10890. {
  10891. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  10892. isAttribute = true;
  10893. checkTypeInst = checkTypeInst->mBaseType;
  10894. }
  10895. if (!isAttribute)
  10896. return;
  10897. auto attributeData = new BfAttributeData();
  10898. bool hasCustomAttribute = false;
  10899. if (mCurTypeInstance->mCustomAttributes != NULL)
  10900. {
  10901. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  10902. {
  10903. if (customAttribute.mType->IsInstanceOf(mCompiler->mAttributeUsageAttributeTypeDef))
  10904. {
  10905. if (customAttribute.mCtorArgs.size() > 0)
  10906. {
  10907. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10908. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  10909. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  10910. }
  10911. if (customAttribute.mCtorArgs.size() == 2)
  10912. {
  10913. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10914. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  10915. {
  10916. attributeData->mFlags = (BfAttributeFlags)constant->mInt32;
  10917. }
  10918. }
  10919. for (auto& setProp : customAttribute.mSetProperties)
  10920. {
  10921. BfPropertyDef* propDef = setProp.mPropertyRef;
  10922. if (propDef->mName == "AllowMultiple")
  10923. {
  10924. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10925. if ((constant != NULL) && (constant->mBool))
  10926. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_DisallowAllowMultiple);
  10927. else
  10928. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_DisallowAllowMultiple);
  10929. }
  10930. else if (propDef->mName == "Inherited")
  10931. {
  10932. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10933. if ((constant != NULL) && (constant->mBool))
  10934. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_NotInherited);
  10935. else
  10936. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_NotInherited);
  10937. }
  10938. else if (propDef->mName == "ValidOn")
  10939. {
  10940. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10941. if (constant != NULL)
  10942. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  10943. }
  10944. else if (propDef->mName == "AlwaysIncludeUser")
  10945. {
  10946. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10947. if (constant != NULL)
  10948. attributeData->mAlwaysIncludeUser = (BfAlwaysIncludeFlags)constant->mInt32;
  10949. }
  10950. }
  10951. hasCustomAttribute = true;
  10952. }
  10953. }
  10954. }
  10955. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  10956. {
  10957. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  10958. attributeData->mFlags = mCurTypeInstance->mBaseType->mAttributeData->mFlags;
  10959. attributeData->mAlwaysIncludeUser = mCurTypeInstance->mBaseType->mAttributeData->mAlwaysIncludeUser;
  10960. }
  10961. mCurTypeInstance->mAttributeData = attributeData;
  10962. }
  10963. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  10964. {
  10965. auto constant = constHolder->GetConstant(irValue);
  10966. if (constant == NULL)
  10967. return false;
  10968. if (constant->mTypeCode != BfTypeCode_StringId)
  10969. return false;
  10970. int stringId = constant->mInt32;
  10971. BfStringPoolEntry* entry = NULL;
  10972. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  10973. {
  10974. str += entry->mString;
  10975. }
  10976. else
  10977. {
  10978. BF_DBG_FATAL("Failed to find string by id");
  10979. }
  10980. return true;
  10981. }
  10982. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  10983. {
  10984. BfVariant variant;
  10985. variant.mTypeCode = BfTypeCode_None;
  10986. BfType* primType = NULL;
  10987. if (value.mType->IsPrimitiveType())
  10988. primType = (BfPrimitiveType*)value.mType;
  10989. else if (value.mType->IsTypedPrimitive())
  10990. primType = value.mType->GetUnderlyingType();
  10991. else if (value.mType->IsInstanceOf(mCompiler->mStringTypeDef))
  10992. primType = value.mType;
  10993. if (primType)
  10994. {
  10995. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  10996. if (constant != NULL)
  10997. {
  10998. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  10999. {
  11000. variant.mUInt64 = 0;
  11001. variant.mTypeCode = BfTypeCode_Let;
  11002. return variant;
  11003. }
  11004. if (constant->mConstType == BfConstType_GlobalVar)
  11005. {
  11006. int stringIdx = GetStringPoolIdx(value.mValue, mBfIRBuilder);
  11007. if (stringIdx != -1)
  11008. {
  11009. variant.mTypeCode = BfTypeCode_StringId;
  11010. variant.mInt64 = stringIdx;
  11011. return variant;
  11012. }
  11013. }
  11014. switch (constant->mTypeCode)
  11015. {
  11016. case BfTypeCode_Boolean:
  11017. case BfTypeCode_Int8:
  11018. case BfTypeCode_UInt8:
  11019. case BfTypeCode_Int16:
  11020. case BfTypeCode_UInt16:
  11021. case BfTypeCode_Int32:
  11022. case BfTypeCode_UInt32:
  11023. case BfTypeCode_Int64:
  11024. case BfTypeCode_UInt64:
  11025. case BfTypeCode_IntPtr:
  11026. case BfTypeCode_UIntPtr:
  11027. case BfTypeCode_IntUnknown:
  11028. case BfTypeCode_UIntUnknown:
  11029. case BfTypeCode_Double:
  11030. case BfTypeCode_Char8:
  11031. case BfTypeCode_Char16:
  11032. case BfTypeCode_Char32:
  11033. case BfTypeCode_StringId:
  11034. variant.mTypeCode = constant->mTypeCode;
  11035. variant.mInt64 = constant->mInt64;
  11036. break;
  11037. case BfTypeCode_Float:
  11038. variant.mTypeCode = constant->mTypeCode;
  11039. variant.mSingle = (float)constant->mDouble;
  11040. break;
  11041. default:
  11042. if (refNode != NULL)
  11043. Fail("Invalid const expression type", refNode);
  11044. break;
  11045. }
  11046. }
  11047. }
  11048. return variant;
  11049. }
  11050. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  11051. {
  11052. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  11053. {
  11054. auto refType = (BfRefType*)typedValue.mType;
  11055. auto elementType = typedValue.mType->GetUnderlyingType();
  11056. if (typedValue.IsAddr())
  11057. {
  11058. if (elementType->IsValuelessType())
  11059. {
  11060. BF_ASSERT(!typedValue.mValue);
  11061. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11062. }
  11063. else
  11064. typedValue = BfTypedValue(mBfIRBuilder->CreateAlignedLoad(typedValue.mValue, elementType->mAlign), elementType, true);
  11065. }
  11066. else
  11067. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11068. if (typedValue.mType->IsValuelessType())
  11069. {
  11070. BF_ASSERT(typedValue.mValue.IsFake());
  11071. }
  11072. if (refType->mRefKind == BfRefType::RefKind_In)
  11073. {
  11074. if (typedValue.mKind == BfTypedValueKind_Addr)
  11075. typedValue.mKind = BfTypedValueKind_ReadOnlyAddr;
  11076. }
  11077. }
  11078. return typedValue;
  11079. }
  11080. BfTypedValue BfModule::SanitizeAddr(BfTypedValue typedValue)
  11081. {
  11082. if (!typedValue)
  11083. return typedValue;
  11084. if (typedValue.mType->IsRef())
  11085. {
  11086. typedValue = LoadValue(typedValue);
  11087. auto copiedVal = BfTypedValue(CreateAlloca(typedValue.mType), typedValue.mType, true);
  11088. mBfIRBuilder->CreateStore(typedValue.mValue, copiedVal.mValue);
  11089. return copiedVal;
  11090. }
  11091. return typedValue;
  11092. }
  11093. BfTypedValue BfModule::ToRef(BfTypedValue typedValue, BfRefType* refType)
  11094. {
  11095. if (refType == NULL)
  11096. refType = CreateRefType(typedValue.mType);
  11097. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (typedValue.mType->IsObjectOrInterface()))
  11098. {
  11099. return LoadValue(typedValue);
  11100. }
  11101. if (refType->mRefKind == BfRefType::RefKind_Mut)
  11102. refType = CreateRefType(typedValue.mType);
  11103. if (!typedValue.mType->IsValuelessType())
  11104. typedValue = MakeAddressable(typedValue, false, true);
  11105. return BfTypedValue(typedValue.mValue, refType);
  11106. }
  11107. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  11108. {
  11109. if (!typedValue.IsAddr())
  11110. return typedValue;
  11111. PopulateType(typedValue.mType);
  11112. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  11113. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  11114. if (typedValue.mValue.IsConst())
  11115. {
  11116. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  11117. if (constantValue != NULL)
  11118. {
  11119. if (constantValue->mConstType == BfConstType_GlobalVar)
  11120. {
  11121. auto globalVar = (BfGlobalVar*)constantValue;
  11122. if (globalVar->mName[0] == '#')
  11123. {
  11124. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  11125. if (result)
  11126. {
  11127. // We want to avoid 'unreachable code' issues from values that
  11128. // are technically constant but change depending on compilation context
  11129. if (mCurMethodState != NULL)
  11130. {
  11131. auto checkScope = mCurMethodState->mCurScope;
  11132. while (checkScope != NULL)
  11133. {
  11134. checkScope->mSupressNextUnreachable = true;
  11135. checkScope = checkScope->mPrevScope;
  11136. }
  11137. }
  11138. return result;
  11139. }
  11140. if (!mIsComptimeModule)
  11141. return GetDefaultTypedValue(typedValue.mType);
  11142. }
  11143. }
  11144. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  11145. {
  11146. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  11147. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  11148. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  11149. auto ceTypedValue = ceDebugger->GetAddr(constantValue);
  11150. if (ceTypedValue)
  11151. {
  11152. if ((typedValue.mType->IsObjectOrInterface()) || (typedValue.mType->IsPointer()) || (typedValue.mType->IsRef()))
  11153. {
  11154. void* data = ceContext->GetMemoryPtr((addr_ce)ceTypedValue.mAddr, sizeof(addr_ce));
  11155. if (data == NULL)
  11156. {
  11157. Fail("Invalid address", refNode);
  11158. return GetDefaultTypedValue(typedValue.mType);
  11159. }
  11160. uint64 dataAddr;
  11161. if (mSystem->mPtrSize == 4)
  11162. dataAddr = *(uint32*)data;
  11163. else
  11164. dataAddr = *(uint64*)data;
  11165. return BfTypedValue(mBfIRBuilder->CreateIntToPtr(
  11166. mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataAddr), mBfIRBuilder->MapType(typedValue.mType)), typedValue.mType);
  11167. }
  11168. auto constVal = ceContext->CreateConstant(this, ceContext->mMemory.mVals + ceTypedValue.mAddr, typedValue.mType);
  11169. if (!constVal)
  11170. {
  11171. Fail("Failed to create const", refNode);
  11172. return GetDefaultTypedValue(typedValue.mType);
  11173. }
  11174. return BfTypedValue(constVal, typedValue.mType);
  11175. }
  11176. }
  11177. }
  11178. }
  11179. BfIRValue loadedVal = typedValue.mValue;
  11180. if (loadedVal)
  11181. {
  11182. if (typedValue.mType->IsVar())
  11183. {
  11184. return BfTypedValue(loadedVal, typedValue.mType, false);
  11185. }
  11186. PopulateType(typedValue.mType, BfPopulateType_Data);
  11187. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile || typedValue.IsVolatile());
  11188. }
  11189. return BfTypedValue(loadedVal, typedValue.mType, false);
  11190. }
  11191. BfTypedValue BfModule::PrepareConst(BfTypedValue& typedValue)
  11192. {
  11193. if (!typedValue.mValue.IsConst())
  11194. return typedValue;
  11195. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  11196. if (constant->mTypeCode == BfTypeCode_StringId)
  11197. return GetTypedValueFromConstant(constant, mBfIRBuilder, typedValue.mType);
  11198. return typedValue;
  11199. }
  11200. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  11201. {
  11202. if (typedValue.IsSplat())
  11203. return AggregateSplat(typedValue);
  11204. if (typedValue.IsAddr())
  11205. return LoadValue(typedValue);
  11206. return typedValue;
  11207. }
  11208. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  11209. {
  11210. if (!typedValue.IsSplat())
  11211. return typedValue;
  11212. BF_ASSERT(!mIsComptimeModule);
  11213. if (typedValue.mType->IsValuelessType())
  11214. return typedValue;
  11215. int elementIdx = 0;
  11216. auto _ExtractValue = [&](BfType* checkType)
  11217. {
  11218. if (valueArrPtr != NULL)
  11219. return valueArrPtr[elementIdx++];
  11220. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  11221. };
  11222. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11223. {
  11224. if (checkType->IsStruct())
  11225. {
  11226. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11227. auto checkTypeInstance = checkType->ToTypeInstance();
  11228. if (checkTypeInstance->mBaseType != NULL)
  11229. {
  11230. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  11231. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  11232. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  11233. }
  11234. if (checkTypeInstance->mIsUnion)
  11235. {
  11236. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11237. if (!unionInnerType->IsValuelessType())
  11238. {
  11239. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  11240. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  11241. }
  11242. if (checkTypeInstance->IsEnum())
  11243. {
  11244. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11245. BfIRValue fieldValue = checkTypeLambda(dscrType);
  11246. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  11247. }
  11248. }
  11249. else
  11250. {
  11251. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11252. {
  11253. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11254. if (fieldInstance->mDataIdx >= 0)
  11255. {
  11256. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  11257. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  11258. }
  11259. }
  11260. }
  11261. return curValue;
  11262. }
  11263. else if (checkType->IsMethodRef())
  11264. {
  11265. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11266. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11267. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11268. {
  11269. BfIRValue fieldValue;
  11270. auto checkType = methodRefType->GetCaptureType(dataIdx);
  11271. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11272. {
  11273. fieldValue = checkTypeLambda(checkType);
  11274. }
  11275. else
  11276. {
  11277. fieldValue = _ExtractValue(checkType);
  11278. }
  11279. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  11280. }
  11281. return curValue;
  11282. }
  11283. else if (!checkType->IsValuelessType())
  11284. {
  11285. return _ExtractValue(checkType);
  11286. }
  11287. return BfIRValue();
  11288. };
  11289. BfIRValue value = checkTypeLambda(typedValue.mType);
  11290. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  11291. }
  11292. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  11293. {
  11294. if (!typedValue.IsSplat())
  11295. return;
  11296. if (typedValue.mType->IsValuelessType())
  11297. return;
  11298. BF_ASSERT(!mIsComptimeModule);
  11299. /*static int sCallIdx = 0;
  11300. if (!mCompiler->mIsResolveOnly)
  11301. sCallIdx++;
  11302. int callIdx = sCallIdx;*/
  11303. int elementIdx = 0;
  11304. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  11305. {
  11306. if (checkType->IsStruct())
  11307. {
  11308. auto checkTypeInstance = checkType->ToTypeInstance();
  11309. if (checkTypeInstance->mBaseType != NULL)
  11310. {
  11311. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  11312. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  11313. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  11314. }
  11315. if (checkTypeInstance->mIsUnion)
  11316. {
  11317. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11318. if (!unionInnerType->IsValuelessType())
  11319. {
  11320. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  11321. checkTypeLambda(unionInnerType, fieldAddrVal);
  11322. }
  11323. if (checkTypeInstance->IsEnum())
  11324. {
  11325. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11326. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  11327. checkTypeLambda(dscrType, fieldAddrVal);
  11328. }
  11329. }
  11330. else
  11331. {
  11332. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11333. {
  11334. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11335. if (fieldInstance->mDataIdx >= 0)
  11336. {
  11337. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  11338. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  11339. }
  11340. }
  11341. }
  11342. }
  11343. else if (checkType->IsMethodRef())
  11344. {
  11345. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11346. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11347. {
  11348. auto dataType = methodRefType->GetCaptureType(dataIdx);
  11349. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  11350. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11351. {
  11352. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  11353. }
  11354. else
  11355. {
  11356. // static int sItrCount = 0;
  11357. // sItrCount++;
  11358. // int curItr = sItrCount;
  11359. // if (curItr == 1)
  11360. // {
  11361. // NOP;
  11362. // }
  11363. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  11364. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  11365. }
  11366. }
  11367. }
  11368. else if (!checkType->IsValuelessType())
  11369. {
  11370. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  11371. mBfIRBuilder->CreateStore(val, curAddrVal);
  11372. }
  11373. };
  11374. checkTypeLambda(typedValue.mType, addrVal);
  11375. }
  11376. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal, bool forceMutable, bool forceAddressable)
  11377. {
  11378. bool wasReadOnly = typedVal.IsReadOnly();
  11379. if ((forceAddressable) ||
  11380. ((typedVal.mType->IsValueType()) &&
  11381. (!typedVal.mType->IsValuelessType())))
  11382. {
  11383. wasReadOnly = true; // Any non-addr is implicitly read-only
  11384. //static int gCallIdx = 0;
  11385. FixValueActualization(typedVal);
  11386. if (typedVal.IsAddr())
  11387. return typedVal;
  11388. BfType* type = typedVal.mType;
  11389. PopulateType(type);
  11390. BfIRValue tempVar;
  11391. if (typedVal.mValue.IsFake())
  11392. tempVar = mBfIRBuilder->GetFakeVal();
  11393. else
  11394. {
  11395. tempVar = CreateAlloca(type);
  11396. if (typedVal.IsSplat())
  11397. AggregateSplatIntoAddr(typedVal, tempVar);
  11398. else
  11399. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  11400. }
  11401. if (forceMutable)
  11402. wasReadOnly = false;
  11403. return BfTypedValue(tempVar, type,
  11404. typedVal.IsThis() ?
  11405. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  11406. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  11407. }
  11408. return LoadValue(typedVal);
  11409. }
  11410. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  11411. {
  11412. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  11413. typedValue.mKind = BfTypedValueKind_Addr;
  11414. return typedValue;
  11415. }
  11416. BfTypedValue BfModule::CopyValue(const BfTypedValue& typedValue)
  11417. {
  11418. return MakeAddressable(LoadValue(typedValue), true);
  11419. }
  11420. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  11421. {
  11422. BF_ASSERT(!mIsComptimeModule);
  11423. BfIRValue val;
  11424. if (typedValue.mValue.IsArg())
  11425. {
  11426. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  11427. if (isAddr != NULL)
  11428. {
  11429. if (wantType != NULL)
  11430. *isAddr = wantType->IsComposite();
  11431. else
  11432. *isAddr = false;
  11433. }
  11434. else if (wantType->IsComposite())
  11435. val = mBfIRBuilder->CreateLoad(val);
  11436. }
  11437. if (!val)
  11438. {
  11439. auto checkMethodState = mCurMethodState;
  11440. while (checkMethodState != NULL)
  11441. {
  11442. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  11443. {
  11444. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  11445. if (decompAddr == typedValue.mValue)
  11446. {
  11447. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  11448. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  11449. {
  11450. // This is really backing for a POINTER to a composite inside a methodRef
  11451. val = mBfIRBuilder->CreateLoad(val);
  11452. }
  11453. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  11454. {
  11455. *isAddr = true;
  11456. return val;
  11457. }
  11458. else
  11459. {
  11460. val = mBfIRBuilder->CreateAlignedLoad(val, wantType->mAlign);
  11461. break;
  11462. }
  11463. }
  11464. }
  11465. if (val)
  11466. break;
  11467. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  11468. {
  11469. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  11470. return mBfIRBuilder->GetFakeVal();
  11471. }
  11472. checkMethodState = checkMethodState->mPrevMethodState;
  11473. }
  11474. }
  11475. if (val)
  11476. {
  11477. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  11478. {
  11479. BF_ASSERT(wantType != NULL);
  11480. if (wantType != NULL)
  11481. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  11482. }
  11483. return val;
  11484. }
  11485. BFMODULE_FATAL(this, "Splat not found");
  11486. return BfIRValue();
  11487. }
  11488. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  11489. {
  11490. int useFieldIdx = fieldIdx;
  11491. BfType* fieldType = NULL;
  11492. if (fieldInstance != NULL)
  11493. {
  11494. fieldType = fieldInstance->mResolvedType;
  11495. if (typedValue.mType->IsUnion())
  11496. {
  11497. if (fieldIdx == 1)
  11498. {
  11499. if (typedValue.IsSplat())
  11500. {
  11501. bool isAddr = false;
  11502. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  11503. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  11504. }
  11505. }
  11506. }
  11507. }
  11508. else
  11509. {
  11510. if (typedValue.mType->IsPayloadEnum())
  11511. {
  11512. auto typeInst = typedValue.mType->ToTypeInstance();
  11513. if (fieldIdx == 1)
  11514. fieldType = typeInst->GetUnionInnerType();
  11515. else if (fieldIdx == 2)
  11516. {
  11517. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  11518. }
  11519. }
  11520. else if (typedValue.mType->IsUnion())
  11521. {
  11522. if (fieldIdx == 1)
  11523. {
  11524. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  11525. if (typedValue.IsSplat())
  11526. {
  11527. bool isAddr = false;
  11528. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  11529. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  11530. }
  11531. }
  11532. }
  11533. }
  11534. BF_ASSERT(typedValue.mType->IsStruct());
  11535. if (typedValue.IsSplat())
  11536. {
  11537. if (typedValue.mType->IsPayloadEnum())
  11538. {
  11539. if (fieldIdx == 1)
  11540. {
  11541. // Payload
  11542. auto typeInst = typedValue.mType->ToTypeInstance();
  11543. auto unionInnerType = typeInst->GetUnionInnerType();
  11544. bool isAddr = false;
  11545. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  11546. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  11547. }
  11548. if (fieldIdx == 2)
  11549. {
  11550. // Discriminator
  11551. auto typeInst = typedValue.mType->ToTypeInstance();
  11552. auto unionInnerType = typeInst->GetUnionInnerType();
  11553. auto dscrType = typeInst->GetDiscriminatorType();
  11554. int argIdx = typedValue.mValue.mId;
  11555. int componentIdx = 0;
  11556. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  11557. bool isAddr;
  11558. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  11559. return BfTypedValue(irVal, dscrType, isAddr);
  11560. }
  11561. }
  11562. int componentIdx = 0;
  11563. BfTypedValue retVal;
  11564. BfFieldInstance* wantFieldInstance = fieldInstance;
  11565. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11566. {
  11567. if (checkType->IsStruct())
  11568. {
  11569. auto checkTypeInstance = checkType->ToTypeInstance();
  11570. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  11571. {
  11572. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  11573. fieldType = checkTypeInstance->GetUnionInnerType();
  11574. checkTypeLambda(fieldType);
  11575. if (checkType->IsEnum())
  11576. {
  11577. // Past discriminator...
  11578. componentIdx++;
  11579. }
  11580. return;
  11581. }
  11582. if (checkTypeInstance->mBaseType != NULL)
  11583. checkTypeLambda(checkTypeInstance->mBaseType);
  11584. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11585. {
  11586. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11587. if (fieldInstance == wantFieldInstance)
  11588. {
  11589. if (fieldInstance->mResolvedType->IsValuelessType())
  11590. {
  11591. retVal = GetDefaultTypedValue(fieldInstance->mResolvedType);
  11592. break;
  11593. }
  11594. bool isAddr = false;
  11595. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  11596. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  11597. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  11598. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  11599. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  11600. {
  11601. retVal = LoadValue(retVal);
  11602. }
  11603. break;
  11604. }
  11605. if (fieldInstance->mDataIdx >= 0)
  11606. checkTypeLambda(fieldInstance->GetResolvedType());
  11607. }
  11608. }
  11609. else if (!checkType->IsValuelessType())
  11610. {
  11611. componentIdx++;
  11612. //argIdx++;
  11613. }
  11614. };
  11615. checkTypeLambda(typedValue.mType);
  11616. BF_ASSERT(retVal);
  11617. return retVal;
  11618. }
  11619. if (typedValue.IsAddr())
  11620. {
  11621. BF_ASSERT(fieldType != NULL);
  11622. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  11623. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  11624. }
  11625. else
  11626. {
  11627. BF_ASSERT(fieldType != NULL);
  11628. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  11629. }
  11630. }
  11631. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  11632. {
  11633. if (typedValue.IsAddr())
  11634. {
  11635. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  11636. return mBfIRBuilder->CreateAlignedLoad(addrVal, typedValue.mType->mAlign);
  11637. }
  11638. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  11639. }
  11640. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  11641. {
  11642. if (isElementIndex)
  11643. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11644. else
  11645. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11646. // if (elementType->IsSizeAligned())
  11647. // {
  11648. // if (isElementIndex)
  11649. // return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11650. // else
  11651. // return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11652. // }
  11653. //
  11654. // auto ptrType = CreatePointerType(elementType);
  11655. // auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  11656. // auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  11657. // auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  11658. // BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  11659. // BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  11660. // return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  11661. }
  11662. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  11663. {
  11664. if (elementType->IsSizeAligned())
  11665. {
  11666. if (isElementIndex)
  11667. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  11668. else
  11669. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11670. }
  11671. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  11672. }
  11673. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  11674. {
  11675. if (modifyType == NULL)
  11676. modifyType = "modify";
  11677. if (typedValue.mType->IsVar())
  11678. return true;
  11679. if (typedValue.IsReadOnly())
  11680. {
  11681. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  11682. return false;
  11683. }
  11684. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  11685. {
  11686. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  11687. return false;
  11688. }
  11689. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  11690. {
  11691. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  11692. return false;
  11693. }
  11694. return true;
  11695. }
  11696. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  11697. {
  11698. // If one is an interface and the other is an impl, B is the impl
  11699. auto implOwner = methodB->GetOwner();
  11700. if (methodA->mMethodDef->mIsLocalMethod)
  11701. {
  11702. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  11703. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  11704. if (sepPosA != sepPosB)
  11705. return false;
  11706. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  11707. return false;
  11708. }
  11709. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  11710. return false;
  11711. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  11712. return false;
  11713. if (methodA->mMethodDef->mHasComptime != methodB->mMethodDef->mHasComptime)
  11714. return false;
  11715. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  11716. return false;
  11717. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  11718. {
  11719. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  11720. return false;
  11721. }
  11722. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  11723. {
  11724. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  11725. return false;
  11726. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  11727. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  11728. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  11729. return false;
  11730. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  11731. return false;
  11732. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  11733. return false;
  11734. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  11735. {
  11736. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  11737. return false;
  11738. }
  11739. }
  11740. int implicitParamCountA = methodA->GetImplicitParamCount();
  11741. int implicitParamCountB = methodB->GetImplicitParamCount();
  11742. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  11743. return false;
  11744. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  11745. return false;
  11746. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  11747. {
  11748. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  11749. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  11750. return false;
  11751. }
  11752. // Compare generic params. Generic params are part of the method signature here
  11753. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  11754. return false;
  11755. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  11756. {
  11757. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  11758. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  11759. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  11760. return false;
  11761. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  11762. return false;
  11763. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  11764. return false;
  11765. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  11766. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  11767. return false;
  11768. }
  11769. return true;
  11770. }
  11771. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  11772. {
  11773. if (!CompareMethodSignatures(methodA, methodB))
  11774. return false;
  11775. if (methodA->mReturnType != methodB->mReturnType)
  11776. return false;
  11777. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  11778. return false;
  11779. return true;
  11780. }
  11781. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  11782. {
  11783. if ((iMethodInst->GetNumGenericParams() != 0) || (methodInstance->GetNumGenericParams() != 0))
  11784. return false;
  11785. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  11786. return false;
  11787. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  11788. return false;
  11789. if (iMethodInst->mMethodDef->mIsOperator)
  11790. {
  11791. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  11792. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  11793. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  11794. return false;
  11795. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  11796. return false;
  11797. }
  11798. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  11799. return false;
  11800. auto selfType = methodInstance->GetOwner();
  11801. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  11802. {
  11803. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  11804. return false;
  11805. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  11806. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  11807. iParamType = ResolveSelfType(iParamType, selfType);
  11808. methodParamType = ResolveSelfType(methodParamType, selfType);
  11809. if (!iParamType->IsGenericParam())
  11810. {
  11811. if (methodParamType != iParamType)
  11812. return false;
  11813. }
  11814. else
  11815. {
  11816. if (!methodParamType->IsGenericParam())
  11817. return false;
  11818. auto genericParamType = (BfGenericParamType*)methodParamType;
  11819. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  11820. return false;
  11821. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  11822. bool hadInterface = false;
  11823. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  11824. if (interfaceConstraint == iParamType)
  11825. hadInterface = true;
  11826. if (!hadInterface)
  11827. return false;
  11828. }
  11829. }
  11830. return true;
  11831. }
  11832. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  11833. {
  11834. BfMethodInstance* methodInstance = methodRef;
  11835. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  11836. {
  11837. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  11838. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  11839. {
  11840. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  11841. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  11842. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  11843. BfMethodRef methodRef = methodInstance;
  11844. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  11845. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  11846. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  11847. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  11848. (mIsReified))
  11849. {
  11850. specializedMethodRefInfo->mHasReifiedRef = true;
  11851. }
  11852. }
  11853. }
  11854. }
  11855. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  11856. {
  11857. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  11858. return BfModuleMethodInstance(methodInstance, BfIRValue());
  11859. if (mBfIRBuilder == NULL)
  11860. return BfModuleMethodInstance(methodInstance, BfIRValue());
  11861. if (methodInstance->GetOwner()->IsFunction())
  11862. {
  11863. // No actual ref needed- not an actual generated function
  11864. return BfModuleMethodInstance(methodInstance, BfIRValue());
  11865. }
  11866. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  11867. if (!isGenFunction)
  11868. AddMethodReference(methodInstance, flags);
  11869. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  11870. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  11871. if (IsSkippingExtraResolveChecks())
  11872. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  11873. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  11874. {
  11875. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  11876. }
  11877. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  11878. if ((methodInstance->mIsIntrinsic) || (methodInstance->mMethodDef->mIsExtern))
  11879. isInlined = false;
  11880. BfMethodRef methodRef = methodInstance;
  11881. if (isInlined)
  11882. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  11883. else
  11884. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  11885. if (!isGenFunction)
  11886. {
  11887. BfIRValue* irFuncPtr = NULL;
  11888. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  11889. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  11890. }
  11891. if (mAwaitingInitFinish)
  11892. FinishInit();
  11893. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  11894. if (!isGenFunction)
  11895. {
  11896. BF_ASSERT(func || methodInstance->mMethodInstanceGroup->mOwner->IsInterface());
  11897. mFuncReferences[methodRef] = func;
  11898. }
  11899. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  11900. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  11901. {
  11902. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  11903. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  11904. // type instance
  11905. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  11906. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  11907. for (auto ownedTypeInst : mOwnedTypeInstances)
  11908. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  11909. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  11910. {
  11911. mIncompleteMethodCount++;
  11912. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  11913. inlineMethodRequest->mType = methodInstance->GetOwner();
  11914. inlineMethodRequest->mFromModule = this;
  11915. inlineMethodRequest->mFunc = func;
  11916. inlineMethodRequest->mFromModuleRevision = mRevision;
  11917. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  11918. inlineMethodRequest->mMethodInstance = methodInstance;
  11919. BF_ASSERT(mIsModuleMutable);
  11920. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  11921. }
  11922. }
  11923. return BfModuleMethodInstance(methodInstance, func);
  11924. }
  11925. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  11926. {
  11927. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  11928. if (mBfIRBuilder == NULL)
  11929. {
  11930. // To allow for custom attribute data
  11931. PrepareForIRWriting(typeInst);
  11932. }
  11933. BfModule* declareModule = this;
  11934. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  11935. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  11936. declareModule = declareModule->mParentModule;
  11937. // Check for attributes
  11938. if (typeInst == mContext->mBfObjectType)
  11939. {
  11940. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  11941. if (methodDecl != NULL)
  11942. {
  11943. auto attributesDirective = methodDecl->mAttributes;
  11944. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  11945. {
  11946. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  11947. sourceClassifier->VisitChild(attributesDirective);
  11948. }
  11949. }
  11950. }
  11951. else
  11952. {
  11953. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  11954. GetMethodCustomAttributes(methodInstance);
  11955. }
  11956. BF_ASSERT(mModuleOptions == NULL);
  11957. if (methodInstance->GetCustomAttributes() != NULL)
  11958. {
  11959. auto project = typeInst->mTypeDef->mProject;
  11960. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  11961. BfModuleOptions wantOptions = moduleOptions;
  11962. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  11963. if (typeOptions != NULL)
  11964. {
  11965. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  11966. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  11967. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  11968. }
  11969. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  11970. {
  11971. StringT<128> attrName;
  11972. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  11973. {
  11974. attrName.Clear();
  11975. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  11976. Array<int>* arrPtr;
  11977. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  11978. {
  11979. for (auto optionsIdx : *arrPtr)
  11980. {
  11981. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  11982. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  11983. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  11984. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  11985. }
  11986. }
  11987. }
  11988. }
  11989. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  11990. {
  11991. auto lastCheckModule = this;
  11992. auto checkModule = this->mNextAltModule;
  11993. while (checkModule != NULL)
  11994. {
  11995. if (*checkModule->mModuleOptions == wantOptions)
  11996. {
  11997. declareModule = checkModule;
  11998. break;
  11999. }
  12000. lastCheckModule = checkModule;
  12001. checkModule = checkModule->mNextAltModule;
  12002. }
  12003. // Not found?
  12004. if (declareModule == this)
  12005. {
  12006. String specModuleName = mModuleName + "@@";
  12007. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  12008. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  12009. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  12010. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  12011. declareModule = new BfModule(mContext, specModuleName);
  12012. declareModule->mProject = project;
  12013. declareModule->mModuleOptions = new BfModuleOptions();
  12014. *declareModule->mModuleOptions = wantOptions;
  12015. declareModule->mParentModule = lastCheckModule;
  12016. declareModule->Init();
  12017. lastCheckModule->mNextAltModule = declareModule;
  12018. }
  12019. }
  12020. }
  12021. declareModule->PrepareForIRWriting(typeInst);
  12022. return declareModule;
  12023. }
  12024. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  12025. {
  12026. if (methodDef->mMethodType == BfMethodType_Init)
  12027. return BfModuleMethodInstance();
  12028. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  12029. {
  12030. // Don't bother inlining for resolve-only
  12031. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12032. }
  12033. if (methodDef->mIsExtern)
  12034. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12035. bool processNow = false;
  12036. bool keepInCurrentModule = false;
  12037. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  12038. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  12039. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  12040. {
  12041. return BfModuleMethodInstance();
  12042. }
  12043. if (methodDef->mIsLocalMethod)
  12044. {
  12045. auto rootMethodState = mCurMethodState->GetRootMethodState();
  12046. BfLocalMethod* localMethod;
  12047. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  12048. {
  12049. // Handle the def in the correct method state
  12050. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  12051. }
  12052. BFMODULE_FATAL(this, "Cannot find local method");
  12053. return BfModuleMethodInstance();
  12054. }
  12055. #ifdef _DEBUG
  12056. for (auto arg : methodGenericArguments)
  12057. BF_ASSERT(!arg->IsVar());
  12058. #endif
  12059. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  12060. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  12061. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  12062. // a FinishInit
  12063. if ((typeInst->IsIncomplete()) &&
  12064. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  12065. {
  12066. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  12067. // for resolve-only because we don't differentiate between reified/unreified there
  12068. if ((methodDef->mIsStatic) /*&& (mIsComptimeModule)*/)
  12069. {
  12070. if (!typeInst->DefineStateAllowsStaticMethods())
  12071. PopulateType(typeInst, BfPopulateType_AllowStaticMethods);
  12072. }
  12073. else
  12074. PopulateType(typeInst, BfPopulateType_Full);
  12075. if (typeInst->mDefineState < BfTypeDefineState_Defined)
  12076. {
  12077. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12078. {
  12079. BfLogSysM("GetMethodInstance (DefineState < BfTypeDefineState_Defined)) bailing due to IsCePaused\n");
  12080. return BfModuleMethodInstance();
  12081. }
  12082. }
  12083. }
  12084. bool tryModuleMethodLookup = false;
  12085. BfModuleMethodInstance moduleMethodInst;
  12086. BfModule* instModule = typeInst->mModule;
  12087. if (keepInCurrentModule)
  12088. {
  12089. // Stay here
  12090. instModule = this;
  12091. }
  12092. if (this == mContext->mUnreifiedModule)
  12093. {
  12094. // Stay in this 'resolve only' module here
  12095. }
  12096. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  12097. {
  12098. BF_ASSERT(this == mContext->mUnreifiedModule);
  12099. }
  12100. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  12101. {
  12102. BF_ASSERT(instModule == mParentModule);
  12103. }
  12104. else if (instModule != this)
  12105. {
  12106. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12107. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  12108. if ((!mIsComptimeModule) && (!mIsReified) && (instModule->mIsReified))
  12109. {
  12110. BF_ASSERT(!mCompiler->mIsResolveOnly);
  12111. // A resolve-only module is specializing a method from a type in a reified module,
  12112. // we need to take care that this doesn't cause anything new to become reified
  12113. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  12114. if (!moduleMethodInstance)
  12115. return moduleMethodInstance;
  12116. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  12117. return moduleMethodInstance;
  12118. }
  12119. else
  12120. {
  12121. if ((!mIsComptimeModule) && (mIsReified) && (!instModule->mIsReified))
  12122. {
  12123. if (!typeInst->IsUnspecializedType())
  12124. {
  12125. if (!instModule->mReifyQueued)
  12126. {
  12127. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  12128. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  12129. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  12130. mContext->mReifyModuleWorkList.Add(instModule);
  12131. instModule->mReifyQueued = true;
  12132. }
  12133. // This ensures that the method will actually be created when it gets reified
  12134. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  12135. specializationRequest->mFromModule = typeInst->mModule;
  12136. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  12137. specializationRequest->Init(typeInst, foreignType, methodDef);
  12138. //specializationRequest->mMethodDef = methodDef;
  12139. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  12140. specializationRequest->mType = typeInst;
  12141. specializationRequest->mFlags = flags;
  12142. }
  12143. }
  12144. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12145. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoReference);
  12146. if (mIsComptimeModule)
  12147. {
  12148. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12149. if (!mCompiler->mIsResolveOnly)
  12150. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification | BfGetMethodInstanceFlag_Unreified | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12151. }
  12152. // Not extern
  12153. // Create the instance in the proper module and then create a reference in this one
  12154. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  12155. if (!moduleMethodInst)
  12156. return moduleMethodInst;
  12157. tryModuleMethodLookup = true;
  12158. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  12159. {
  12160. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  12161. }
  12162. }
  12163. }
  12164. if (tryModuleMethodLookup)
  12165. {
  12166. SetMethodDependency(moduleMethodInst.mMethodInstance);
  12167. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  12168. }
  12169. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  12170. {
  12171. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  12172. if (moduleMethodInstance)
  12173. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  12174. return moduleMethodInst;
  12175. }
  12176. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  12177. bool hadConcreteInterfaceGenericArgument = false;
  12178. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  12179. isReified = false;
  12180. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  12181. {
  12182. isReified = false;
  12183. }
  12184. BfTypeVector sanitizedMethodGenericArguments;
  12185. SizedArray<BfProject*, 4> projectList;
  12186. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  12187. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  12188. isUnspecializedPass = false;
  12189. // Check for whether we are an extension method from a project that does not hold the root type, AND that isn't already the project for this type
  12190. bool isExternalExtensionMethod = false;
  12191. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  12192. {
  12193. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) &&
  12194. (methodDef->mDeclaringType != NULL) &&
  12195. (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  12196. {
  12197. auto specProject = methodDef->mDeclaringType->mProject;
  12198. isExternalExtensionMethod = true;
  12199. if (typeInst->IsGenericTypeInstance())
  12200. {
  12201. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12202. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12203. genericTypeInst->GenerateProjectsReferenced();
  12204. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  12205. {
  12206. // This is a generic type where a generic param is already confined to the project in question
  12207. isExternalExtensionMethod = false;
  12208. }
  12209. }
  12210. if (isExternalExtensionMethod)
  12211. {
  12212. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  12213. projectList.push_back(methodDef->mDeclaringType->mProject);
  12214. }
  12215. }
  12216. }
  12217. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  12218. {
  12219. int typeProjectsCounts = 0;
  12220. if (typeInst->IsGenericTypeInstance())
  12221. {
  12222. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12223. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12224. genericTypeInst->GenerateProjectsReferenced();
  12225. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  12226. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  12227. }
  12228. else
  12229. {
  12230. typeProjectsCounts = 1;
  12231. projectList.Insert(0, typeInst->mTypeDef->mProject);
  12232. }
  12233. isUnspecializedPass = true;
  12234. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  12235. {
  12236. auto genericArgType = methodGenericArguments[genericArgIdx];
  12237. //BF_ASSERT(!genericArgType->IsRef());
  12238. if (genericArgType->IsConcreteInterfaceType())
  12239. {
  12240. hadConcreteInterfaceGenericArgument = true;
  12241. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  12242. genericArgType = concreteInterfaceType->mInterface;
  12243. }
  12244. if (genericArgType->IsGenericParam())
  12245. {
  12246. auto genericParam = (BfGenericParamType*) genericArgType;
  12247. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  12248. isUnspecializedPass = false;
  12249. }
  12250. else
  12251. {
  12252. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  12253. isUnspecializedPass = false;
  12254. }
  12255. sanitizedMethodGenericArguments.push_back(genericArgType);
  12256. }
  12257. if ((int)projectList.size() > typeProjectsCounts)
  12258. {
  12259. // Just leave the new items
  12260. projectList.RemoveRange(0, typeProjectsCounts);
  12261. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  12262. {
  12263. return lhs->mName < rhs->mName;
  12264. });
  12265. }
  12266. else
  12267. {
  12268. projectList.Clear();
  12269. }
  12270. }
  12271. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  12272. BfMethodInstanceGroup* methodInstGroup = NULL;
  12273. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12274. {
  12275. BF_ASSERT(!typeInst->IsInterface());
  12276. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  12277. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  12278. {
  12279. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  12280. // if (checkGroup.mDefault == NULL)
  12281. // {
  12282. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  12283. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  12284. // methodInstGroup = &checkGroup;
  12285. // break;
  12286. // }
  12287. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  12288. {
  12289. methodInstGroup = &checkGroup;
  12290. break;
  12291. }
  12292. }
  12293. if (methodInstGroup == NULL)
  12294. {
  12295. if (lookupMethodGenericArguments.size() != 0)
  12296. {
  12297. BF_ASSERT((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0);
  12298. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12299. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12300. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12301. }
  12302. else
  12303. {
  12304. // Allocate a new entry
  12305. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  12306. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  12307. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  12308. methodInstGroup->mOwner = typeInst;
  12309. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12310. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12311. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  12312. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12313. else
  12314. {
  12315. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  12316. if (!mIsScratchModule)
  12317. mOnDemandMethodCount++;
  12318. }
  12319. }
  12320. }
  12321. }
  12322. else
  12323. {
  12324. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  12325. }
  12326. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12327. {
  12328. if (typeInst->mDefineState > BfTypeDefineState_DefinedAndMethodsSlotted)
  12329. {
  12330. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  12331. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12332. }
  12333. }
  12334. BfIRFunction prevIRFunc;
  12335. bool doingRedeclare = false;
  12336. BfMethodInstance* methodInstance = NULL;
  12337. auto _SetReified = [&]()
  12338. {
  12339. if (!mCompiler->mIsResolveOnly)
  12340. BF_ASSERT(mCompiler->mCompileState <= BfCompiler::CompileState_Normal);
  12341. methodInstance->mIsReified = true;
  12342. };
  12343. if (lookupMethodGenericArguments.size() == 0)
  12344. {
  12345. methodInstance = methodInstGroup->mDefault;
  12346. if ((methodInstance != NULL) && ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0))
  12347. return methodInstance;
  12348. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  12349. {
  12350. MarkDerivedDirty(typeInst);
  12351. if (!HasCompiledOutput())
  12352. {
  12353. BfLogSysM("Marking non-compiled-output module method instance as reified: %p\n", methodInstance);
  12354. _SetReified();
  12355. CheckHotMethod(methodInstance, "");
  12356. }
  12357. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  12358. {
  12359. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  12360. // the specializations to handle that for us
  12361. return BfModuleMethodInstance(methodInstance);
  12362. }
  12363. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  12364. {
  12365. if (methodDef->mIsAbstract)
  12366. {
  12367. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12368. _SetReified();
  12369. }
  12370. else
  12371. {
  12372. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12373. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  12374. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  12375. doingRedeclare = true;
  12376. mOnDemandMethodCount++;
  12377. VerifyOnDemandMethods();
  12378. }
  12379. }
  12380. else
  12381. {
  12382. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  12383. // We haven't processed it yet
  12384. _SetReified();
  12385. CheckHotMethod(methodInstance, "");
  12386. if (methodInstance->mDeclModule == this)
  12387. {
  12388. if (methodInstance->mMethodProcessRequest != NULL)
  12389. {
  12390. // Disconnect method process request
  12391. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  12392. }
  12393. }
  12394. else
  12395. {
  12396. if (methodInstance->mMethodProcessRequest != NULL)
  12397. {
  12398. // Disconnect method process request
  12399. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  12400. methodInstance->mMethodProcessRequest = NULL;
  12401. }
  12402. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  12403. {
  12404. // Add new request in proper module
  12405. methodInstance->mDeclModule = this;
  12406. }
  12407. else
  12408. {
  12409. if (methodInstance->mDeclModule == NULL)
  12410. {
  12411. //
  12412. }
  12413. else if (methodInstance->mDeclModule != this)
  12414. {
  12415. // Is from specialized module?
  12416. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  12417. }
  12418. }
  12419. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12420. {
  12421. methodInstance->mIRFunction = BfIRFunction();
  12422. if (!mIsModuleMutable)
  12423. StartExtension();
  12424. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  12425. {
  12426. StringT<512> mangledName;
  12427. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  12428. bool isIntrinsic = false;
  12429. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  12430. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  12431. }
  12432. }
  12433. AddMethodToWorkList(methodInstance);
  12434. }
  12435. }
  12436. }
  12437. }
  12438. else
  12439. {
  12440. if (methodInstGroup->mDefault == NULL)
  12441. {
  12442. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12443. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12444. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12445. }
  12446. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  12447. if (methodInstGroup->mMethodSpecializationMap == NULL)
  12448. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  12449. BfMethodInstance** methodInstancePtr = NULL;
  12450. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  12451. {
  12452. methodInstance = *methodInstancePtr;
  12453. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  12454. return methodInstance;
  12455. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  12456. {
  12457. BfLogSysM("Setting mRequestedByAutocomplete=false for method instance %p\n", methodInstance);
  12458. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  12459. if (methodInstance->mMethodProcessRequest == NULL)
  12460. AddMethodToWorkList(methodInstance);
  12461. methodInstance->mRequestedByAutocomplete = false;
  12462. }
  12463. if ((isReified) && (!methodInstance->mIsReified))
  12464. {
  12465. MarkDerivedDirty(typeInst);
  12466. if (methodInstance->mHasBeenProcessed)
  12467. {
  12468. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  12469. delete methodInstance;
  12470. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12471. methodInstance = NULL;
  12472. }
  12473. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12474. {
  12475. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  12476. delete methodInstance;
  12477. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12478. methodInstance = NULL;
  12479. }
  12480. else
  12481. {
  12482. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  12483. // We haven't processed it yet
  12484. _SetReified();
  12485. CheckHotMethod(methodInstance, "");
  12486. if (methodInstance->mMethodProcessRequest == NULL)
  12487. AddMethodToWorkList(methodInstance);
  12488. }
  12489. }
  12490. }
  12491. }
  12492. if ((methodInstance != NULL) && (!doingRedeclare))
  12493. {
  12494. SetMethodDependency(methodInstance);
  12495. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  12496. {
  12497. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  12498. BF_ASSERT(!methodInstance->mIsReified);*/
  12499. if (methodInstance->mIsReified != isReified)
  12500. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  12501. if ((!isReified) &&
  12502. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  12503. {
  12504. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  12505. methodInstance->mIRFunction = BfIRFunction();
  12506. }
  12507. methodInstance->mIsReified = isReified;
  12508. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  12509. {
  12510. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  12511. }
  12512. if (!methodInstance->mMethodDef->mIsAbstract)
  12513. {
  12514. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  12515. {
  12516. // Wait until unreified
  12517. }
  12518. else
  12519. AddMethodToWorkList(methodInstance);
  12520. }
  12521. else
  12522. {
  12523. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  12524. auto owningModule = methodInstance->GetOwner()->mModule;
  12525. if (!owningModule->mIsScratchModule)
  12526. {
  12527. owningModule->mOnDemandMethodCount--;
  12528. owningModule->VerifyOnDemandMethods();
  12529. }
  12530. }
  12531. }
  12532. if (mExtensionCount > 0)
  12533. {
  12534. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  12535. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  12536. {
  12537. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  12538. if (mAwaitingInitFinish)
  12539. FinishInit();
  12540. // We need to refer to a function that was defined in a prior module
  12541. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12542. if (methodInstance->mIsIntrinsic)
  12543. isInlined = false;
  12544. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  12545. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  12546. methodInstance->mDeclModule = this;
  12547. // Add this inlined def to ourselves
  12548. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12549. {
  12550. mIncompleteMethodCount++;
  12551. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12552. inlineMethodRequest->mType = typeInst;
  12553. inlineMethodRequest->mFromModule = this;
  12554. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  12555. inlineMethodRequest->mFromModuleRevision = mRevision;
  12556. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  12557. inlineMethodRequest->mMethodInstance = methodInstance;
  12558. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12559. BF_ASSERT(mIsModuleMutable);
  12560. }
  12561. }
  12562. }
  12563. if (IsSkippingExtraResolveChecks())
  12564. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12565. else
  12566. {
  12567. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12568. return methodInstance;
  12569. if (methodInstance->mDeclModule != this)
  12570. return ReferenceExternalMethodInstance(methodInstance, flags);
  12571. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  12572. {
  12573. auto importKind = methodInstance->GetImportCallKind();
  12574. if (importKind != BfImportCallKind_None)
  12575. {
  12576. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  12577. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  12578. auto func = CreateDllImportGlobalVar(methodInstance, true);
  12579. BF_ASSERT(func);
  12580. mFuncReferences[methodInstance] = func;
  12581. }
  12582. }
  12583. return BfModuleMethodInstance(methodInstance);
  12584. }
  12585. }
  12586. if (!doingRedeclare)
  12587. {
  12588. BfModule* specModule = NULL;
  12589. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  12590. {
  12591. specModule = GetSpecializedMethodModule(projectList);
  12592. }
  12593. if ((specModule != NULL) && (specModule != this))
  12594. {
  12595. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  12596. if (mAwaitingInitFinish)
  12597. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  12598. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12599. return specMethodInstance.mMethodInstance;
  12600. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  12601. }
  12602. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  12603. {
  12604. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  12605. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  12606. }
  12607. }
  12608. if (methodInstance == NULL)
  12609. {
  12610. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12611. {
  12612. BfLogSysM("GetMethodInstance (methodInstance == NULL) bailing due to IsCePaused\n");
  12613. return BfModuleMethodInstance();
  12614. }
  12615. if (lookupMethodGenericArguments.size() == 0)
  12616. {
  12617. BF_ASSERT(methodInstGroup->mDefault == NULL);
  12618. methodInstance = new BfMethodInstance();
  12619. methodInstGroup->mDefault = methodInstance;
  12620. BF_ASSERT(typeInst->mDefineState > BfTypeDefineState_Declared);
  12621. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  12622. }
  12623. else
  12624. {
  12625. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  12626. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12627. depthExceeded = true;
  12628. if (depthExceeded)
  12629. {
  12630. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  12631. return BfModuleMethodInstance();
  12632. }
  12633. BfMethodInstance** methodInstancePtr = NULL;
  12634. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  12635. BF_ASSERT(added);
  12636. methodInstance = new BfMethodInstance();
  12637. *methodInstancePtr = methodInstance;
  12638. if (mCompiler->IsAutocomplete())
  12639. methodInstance->mRequestedByAutocomplete = true;
  12640. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  12641. }
  12642. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  12643. methodInstance->mIRFunction = prevIRFunc; // Take it over
  12644. }
  12645. methodInstance->mMethodDef = methodDef;
  12646. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  12647. methodInstance->mMethodInstanceGroup = methodInstGroup;
  12648. methodInstance->mIsReified = isReified;
  12649. SetupMethodIdHash(methodInstance);
  12650. if (hadConcreteInterfaceGenericArgument)
  12651. methodInstance->mIgnoreBody = true;
  12652. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12653. {
  12654. methodInstance->mIsForeignMethodDef = true;
  12655. BF_ASSERT(foreignType != NULL);
  12656. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  12657. }
  12658. if ((typeInst->IsInstanceOf(mCompiler->mValueTypeTypeDef)) && (methodDef->mName == BF_METHODNAME_EQUALS))
  12659. {
  12660. if (!lookupMethodGenericArguments.empty())
  12661. {
  12662. auto compareType = lookupMethodGenericArguments[0];
  12663. PopulateType(compareType, BfPopulateType_Data);
  12664. if (compareType->IsSplattable())
  12665. methodInstance->mAlwaysInline = true;
  12666. }
  12667. }
  12668. if (methodDef->mMethodType == BfMethodType_Init)
  12669. {
  12670. methodInstance->mMangleWithIdx = true;
  12671. }
  12672. BF_ASSERT(typeInst == methodInstance->GetOwner());
  12673. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12674. if (isUnspecializedPass)
  12675. {
  12676. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  12677. {
  12678. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  12679. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  12680. }
  12681. }
  12682. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  12683. {
  12684. if (!sanitizedMethodGenericArguments.IsEmpty())
  12685. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  12686. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  12687. {
  12688. Fail("Internal error");
  12689. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  12690. return NULL;
  12691. }
  12692. for (auto genericArg : sanitizedMethodGenericArguments)
  12693. {
  12694. if (genericArg->IsPrimitiveType())
  12695. genericArg = GetWrappedStructType(genericArg);
  12696. if (genericArg != NULL)
  12697. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  12698. }
  12699. }
  12700. // Generic constraints
  12701. if (!methodDef->mGenericParams.IsEmpty())
  12702. {
  12703. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  12704. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  12705. {
  12706. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  12707. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12708. }
  12709. }
  12710. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  12711. {
  12712. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  12713. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12714. }
  12715. bool addToWorkList = !processNow;
  12716. if (mCompiler->GetAutoComplete() != NULL)
  12717. {
  12718. if (typeInst->IsSpecializedByAutoCompleteMethod())
  12719. addToWorkList = false;
  12720. if (methodInstance->mRequestedByAutocomplete)
  12721. addToWorkList = false;
  12722. }
  12723. BfModule* declareModule;
  12724. //
  12725. {
  12726. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  12727. declareModule = GetOrCreateMethodModule(methodInstance);
  12728. }
  12729. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  12730. declareModule = methodInstance->mDeclModule;
  12731. BF_ASSERT(declareModule != NULL);
  12732. methodInstance->mDeclModule = declareModule;
  12733. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  12734. {
  12735. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  12736. // of a reified module -
  12737. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  12738. // BUT if we don't reify it then we have to remove the body after processing.
  12739. // But if we declare it in the unreified module module and then end up needing to reify it then we need to re-declare it in
  12740. // the proper reified module.
  12741. declareModule = mContext->mUnreifiedModule;
  12742. }
  12743. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  12744. {
  12745. if (!methodInstance->mIsReified)
  12746. {
  12747. declareModule = mContext->mUnreifiedModule;
  12748. }
  12749. else
  12750. {
  12751. declareModule->PrepareForIRWriting(methodInstance->GetOwner());
  12752. }
  12753. }
  12754. SetMethodDependency(methodInstance);
  12755. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  12756. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  12757. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  12758. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  12759. {
  12760. // For mixins we only process the unspecialized version
  12761. addToWorkList = false;
  12762. }
  12763. if (((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0) && (methodInstGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  12764. {
  12765. addToWorkList = false;
  12766. }
  12767. // if ((flags & BfGetMethodInstanceFlag_NoReference) != 0)
  12768. // addToWorkList = false;
  12769. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  12770. if (processNow)
  12771. {
  12772. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  12773. ProcessMethod(methodInstance);
  12774. }
  12775. if (IsSkippingExtraResolveChecks())
  12776. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12777. if (methodInstance->mDeclModule != this)
  12778. return ReferenceExternalMethodInstance(methodInstance, flags);
  12779. return BfModuleMethodInstance(methodInstance);
  12780. }
  12781. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  12782. {
  12783. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  12784. if (methodInstance->mIsForeignMethodDef)
  12785. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  12786. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  12787. }
  12788. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  12789. {
  12790. if (!methodInstance->mMethodDef->mIsLocalMethod)
  12791. return NULL;
  12792. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  12793. if (outerLocal == NULL)
  12794. return NULL;
  12795. BfTypeVector genericArgs;
  12796. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  12797. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  12798. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  12799. }
  12800. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  12801. {
  12802. HashContext hashCtx;
  12803. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  12804. {
  12805. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  12806. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  12807. if (methodInstance->GetNumGenericArguments() != 0)
  12808. {
  12809. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  12810. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  12811. hashCtx.Mixin(methodGenericArg->mTypeId);
  12812. }
  12813. };
  12814. _MixinMethodInstance(methodInstance);
  12815. if (methodInstance->mMethodDef->mIsLocalMethod)
  12816. {
  12817. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  12818. if (outmostMethodInstance != NULL)
  12819. {
  12820. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  12821. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  12822. }
  12823. }
  12824. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  12825. }
  12826. bool BfModule::CheckUseMethodInstance(BfMethodInstance* methodInstance, BfAstNode* refNode)
  12827. {
  12828. if (methodInstance->mHasBeenDeclared)
  12829. return true;
  12830. Fail(StrFormat("Circular reference in method instance '%s'", MethodToString(methodInstance).c_str()), refNode);
  12831. return false;
  12832. }
  12833. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  12834. {
  12835. BfIRValue globalValue;
  12836. BfIRValue* globalValuePtr = NULL;
  12837. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  12838. {
  12839. globalValue = *globalValuePtr;
  12840. }
  12841. if (!globalValue)
  12842. {
  12843. // This is necessary to reify the interface type
  12844. PopulateType(ifaceType);
  12845. StringT<512> slotVarName;
  12846. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  12847. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  12848. BfIRValue value;
  12849. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  12850. {
  12851. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  12852. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  12853. int virtSlotIdx = ifaceType->mSlotNum + 1;
  12854. value = GetConstValue32(virtSlotIdx);*/
  12855. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  12856. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  12857. }
  12858. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  12859. mInterfaceSlotRefs[ifaceType] = globalValue;
  12860. }
  12861. return mBfIRBuilder->CreateAlignedLoad(globalValue/*, "slotOfs"*/, 4);
  12862. }
  12863. void BfModule::HadSlotCountDependency()
  12864. {
  12865. if (mCompiler->mIsResolveOnly)
  12866. return;
  12867. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  12868. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  12869. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  12870. }
  12871. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  12872. {
  12873. if (str == "#IsComptime")
  12874. {
  12875. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsComptimeModule ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  12876. }
  12877. if (str == "#IsBuilding")
  12878. {
  12879. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (!mCompiler->mIsResolveOnly) ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  12880. }
  12881. if (str == "#IsReified")
  12882. {
  12883. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsReified ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  12884. }
  12885. if (str == "#CompileRev")
  12886. {
  12887. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mRevision), GetPrimitiveType(BfTypeCode_Int32));
  12888. }
  12889. if (str == "#NextId")
  12890. {
  12891. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)++mCompiler->mUniqueId), GetPrimitiveType(BfTypeCode_Int32));
  12892. }
  12893. if (str == "#ModuleName")
  12894. {
  12895. return BfTypedValue(GetStringObjectValue(mModuleName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12896. }
  12897. if (str == "#ProjectName")
  12898. {
  12899. if (mProject != NULL)
  12900. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12901. }
  12902. if (str == "#AllocStackCount")
  12903. {
  12904. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mOptions.mAllocStackCount), GetPrimitiveType(BfTypeCode_Int32));
  12905. }
  12906. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  12907. {
  12908. if (str == "#CallerLineNum")
  12909. {
  12910. return BfTypedValue(GetConstValue(mCurMethodState->mMixinState->mInjectFilePosition.mCurLine + 1), GetPrimitiveType(BfTypeCode_Int32));
  12911. }
  12912. else if (str == "#CallerFilePath")
  12913. {
  12914. String filePath = "";
  12915. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  12916. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  12917. return BfTypedValue(GetStringObjectValue(filePath), ResolveTypeDef(mCompiler->mStringTypeDef));
  12918. }
  12919. else if (str == "#CallerFileName")
  12920. {
  12921. String filePath = "";
  12922. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  12923. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  12924. return BfTypedValue(GetStringObjectValue(GetFileName(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  12925. }
  12926. else if (str == "#CallerFileDir")
  12927. {
  12928. String filePath = "";
  12929. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  12930. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  12931. return BfTypedValue(GetStringObjectValue(GetFileDir(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  12932. }
  12933. else if (str == "#CallerTypeName")
  12934. {
  12935. String typeName = "";
  12936. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  12937. typeName = TypeToString(mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner());
  12938. return BfTypedValue(GetStringObjectValue(typeName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12939. }
  12940. else if (str == "#CallerType")
  12941. {
  12942. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  12943. BfType* type = NULL;
  12944. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  12945. type = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  12946. if (type != NULL)
  12947. {
  12948. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  12949. return BfTypedValue(CreateTypeDataRef(type), typeType);
  12950. }
  12951. }
  12952. else if (str == "#CallerMemberName")
  12953. {
  12954. String memberName = "";
  12955. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  12956. memberName = MethodToString(mCurMethodState->mMixinState->mMixinMethodInstance);
  12957. return BfTypedValue(GetStringObjectValue(memberName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12958. }
  12959. else if (str == "#CallerProject")
  12960. {
  12961. BfProject* project = NULL;
  12962. project = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mProject;
  12963. if (project != NULL)
  12964. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12965. }
  12966. }
  12967. if (str == "#TimeLocal")
  12968. {
  12969. time_t rawtime;
  12970. time(&rawtime);
  12971. tm* timeinfo = localtime(&rawtime);
  12972. char result[32];
  12973. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  12974. 1900 + timeinfo->tm_year,
  12975. timeinfo->tm_mon,
  12976. timeinfo->tm_mday,
  12977. timeinfo->tm_hour,
  12978. timeinfo->tm_min,
  12979. timeinfo->tm_sec);
  12980. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  12981. }
  12982. return BfTypedValue();
  12983. }
  12984. BfTypedValue BfModule::GetCompilerFieldValue(BfTypedValue typedValue)
  12985. {
  12986. if (!typedValue.IsAddr())
  12987. return BfTypedValue();
  12988. if (typedValue.mValue.IsConst())
  12989. {
  12990. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  12991. if (constantValue != NULL)
  12992. {
  12993. if (constantValue->mConstType == BfConstType_GlobalVar)
  12994. {
  12995. auto globalVar = (BfGlobalVar*)constantValue;
  12996. if (globalVar->mName[0] == '#')
  12997. {
  12998. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  12999. return result;
  13000. }
  13001. }
  13002. }
  13003. }
  13004. return BfTypedValue();
  13005. }
  13006. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  13007. {
  13008. BfIRValue globalValue;
  13009. auto fieldDef = fieldInstance->GetFieldDef();
  13010. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  13011. {
  13012. if (fieldInstance->mConstIdx != -1)
  13013. {
  13014. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  13015. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  13016. }
  13017. else
  13018. {
  13019. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  13020. }
  13021. }
  13022. if ((mIsScratchModule) && (mCompiler->mIsResolveOnly) && (!fieldInstance->mOwner->IsInstanceOf(mCompiler->mCompilerTypeDef)))
  13023. {
  13024. // Just fake it for the extern and unspecialized modules
  13025. // We can't do this for compilation because unreified methods with default params need to get actual global variable refs
  13026. return BfTypedValue(mBfIRBuilder->CreateConstNull(), fieldInstance->GetResolvedType(), true);
  13027. }
  13028. BfIRValue* globalValuePtr = NULL;
  13029. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  13030. {
  13031. globalValue = *globalValuePtr;
  13032. BF_ASSERT(globalValue);
  13033. auto globalVar = (BfGlobalVar*)mBfIRBuilder->GetConstant(globalValue);
  13034. if ((globalVar->mStreamId == -1) && (!mBfIRBuilder->mIgnoreWrites))
  13035. {
  13036. mBfIRBuilder->MapType(fieldInstance->mResolvedType);
  13037. mBfIRBuilder->CreateGlobalVariable(globalValue);
  13038. }
  13039. }
  13040. else
  13041. {
  13042. StringT<512> staticVarName;
  13043. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  13044. auto typeType = fieldInstance->GetResolvedType();
  13045. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  13046. {
  13047. typeType = typeType->GetUnderlyingType();
  13048. }
  13049. if (mIsComptimeModule)
  13050. {
  13051. mCompiler->mCeMachine->QueueStaticField(fieldInstance, staticVarName);
  13052. }
  13053. PopulateType(typeType);
  13054. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  13055. {
  13056. BfIRType irType = mBfIRBuilder->MapType(typeType);
  13057. if (fieldInstance->IsAppendedObject())
  13058. irType = mBfIRBuilder->MapTypeInst(typeType->ToTypeInstance());
  13059. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  13060. globalValue = mBfIRBuilder->CreateGlobalVariable(
  13061. irType,
  13062. false,
  13063. BfIRLinkageType_External,
  13064. BfIRValue(),
  13065. staticVarName,
  13066. IsThreadLocal(fieldInstance));
  13067. BF_ASSERT(globalValue);
  13068. mStaticFieldRefs[fieldInstance] = globalValue;
  13069. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  13070. }
  13071. }
  13072. auto type = fieldInstance->GetResolvedType();
  13073. if (type->IsValuelessType())
  13074. return BfTypedValue(globalValue, type);
  13075. if (fieldDef->mIsVolatile)
  13076. return BfTypedValue(globalValue, type, BfTypedValueKind_VolatileAddr);
  13077. return BfTypedValue(globalValue, type, !fieldDef->mIsConst && !fieldInstance->IsAppendedObject());
  13078. }
  13079. BfFieldInstance* BfModule::GetFieldInstance(BfTypeInstance* typeInst, int fieldIdx, const char* fieldName)
  13080. {
  13081. if (typeInst->IsDataIncomplete())
  13082. PopulateType(typeInst);
  13083. if (fieldIdx >= typeInst->mFieldInstances.mSize)
  13084. {
  13085. Fail(StrFormat("Invalid field data in type '%s'", TypeToString(typeInst).c_str()));
  13086. return 0;
  13087. }
  13088. return &typeInst->mFieldInstances[fieldIdx];
  13089. }
  13090. void BfModule::MarkUsingThis()
  13091. {
  13092. auto useMethodState = mCurMethodState;
  13093. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13094. {
  13095. useMethodState = useMethodState->mPrevMethodState;
  13096. }
  13097. if ((useMethodState != NULL) && (!useMethodState->mLocals.IsEmpty()))
  13098. {
  13099. auto localVar = useMethodState->mLocals[0];
  13100. if (localVar->mIsThis)
  13101. localVar->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13102. }
  13103. }
  13104. BfTypedValue BfModule::GetThis(bool markUsing)
  13105. {
  13106. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  13107. {
  13108. if (mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis)
  13109. return mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis;
  13110. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  13111. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  13112. if ((activeFrame != NULL) && (activeFrame->mFunction->mDbgInfo != NULL))
  13113. {
  13114. for (auto& dbgVar : activeFrame->mFunction->mDbgInfo->mVariables)
  13115. {
  13116. if (dbgVar.mName == "this")
  13117. return BfTypedValue(mBfIRBuilder->CreateConstAggCE(mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs), dbgVar.mType,
  13118. dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  13119. }
  13120. }
  13121. return BfTypedValue();
  13122. }
  13123. auto useMethodState = mCurMethodState;
  13124. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13125. {
  13126. useMethodState = useMethodState->mPrevMethodState;
  13127. }
  13128. if (useMethodState != NULL)
  13129. {
  13130. // Fake a 'this' for var field resolution
  13131. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  13132. {
  13133. auto thisType = mCurTypeInstance;
  13134. if (thisType->IsValueType())
  13135. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  13136. else
  13137. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  13138. }
  13139. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  13140. {
  13141. return BfTypedValue();
  13142. }
  13143. }
  13144. else
  13145. {
  13146. //TODO: Do we allow useMethodState to be NULL anymore?
  13147. return BfTypedValue();
  13148. }
  13149. // Check mixin state for 'this'
  13150. {
  13151. auto checkMethodState = mCurMethodState;
  13152. while (checkMethodState != NULL)
  13153. {
  13154. if (checkMethodState->mMixinState != NULL)
  13155. {
  13156. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  13157. if (thisValue.HasType())
  13158. {
  13159. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13160. if (!thisValue.mType->IsValueType())
  13161. thisValue = LoadValue(thisValue);
  13162. return thisValue;
  13163. }
  13164. }
  13165. checkMethodState = checkMethodState->mPrevMethodState;
  13166. }
  13167. }
  13168. auto curMethodInstance = mCurMethodInstance;
  13169. if (useMethodState->mMethodInstance != NULL)
  13170. curMethodInstance = useMethodState->mMethodInstance;
  13171. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  13172. {
  13173. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  13174. {
  13175. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  13176. if (constLocal.mIsThis)
  13177. {
  13178. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  13179. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  13180. }
  13181. }
  13182. return BfTypedValue();
  13183. }
  13184. if (useMethodState->mLocals.IsEmpty())
  13185. {
  13186. // This can happen in rare non-capture cases, such as when we need to do a const expression resolve for a sized-array return type on a local method
  13187. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  13188. return BfTypedValue();
  13189. }
  13190. auto thisLocal = useMethodState->mLocals[0];
  13191. BF_ASSERT(thisLocal->mIsThis);
  13192. bool preferValue = !IsTargetingBeefBackend();
  13193. if (!thisLocal->mAddr)
  13194. preferValue = true;
  13195. bool usedVal = false;
  13196. BfIRValue thisValue;
  13197. if ((preferValue) && (!thisLocal->mIsLowered))
  13198. {
  13199. thisValue = thisLocal->mValue;
  13200. usedVal = true;
  13201. }
  13202. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  13203. thisValue = thisLocal->mAddr;
  13204. else
  13205. thisValue = mBfIRBuilder->CreateAlignedLoad(thisLocal->mAddr, thisLocal->mResolvedType->mAlign);
  13206. if (markUsing)
  13207. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13208. if (useMethodState->mClosureState != NULL)
  13209. {
  13210. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  13211. if (closureTypeInst != NULL)
  13212. {
  13213. if (closureTypeInst->mFieldInstances.size() > 0)
  13214. {
  13215. auto& field = closureTypeInst->mFieldInstances[0];
  13216. auto fieldDef = field.GetFieldDef();
  13217. if (fieldDef->mName == "__this")
  13218. {
  13219. if (mCurMethodState->mClosureState->mCapturing)
  13220. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  13221. // This is a captured 'this'
  13222. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  13223. if (field.mResolvedType->IsRef())
  13224. {
  13225. auto refType = (BfRefType*)field.mResolvedType;
  13226. auto underlyingType = refType->GetUnderlyingType();
  13227. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  13228. }
  13229. if (field.mResolvedType->IsObject())
  13230. {
  13231. result = LoadValue(result);
  13232. result.mKind = BfTypedValueKind_ThisValue;
  13233. }
  13234. else
  13235. {
  13236. if (fieldDef->mIsReadOnly)
  13237. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  13238. else
  13239. result.mKind = BfTypedValueKind_ThisAddr;
  13240. }
  13241. return result;
  13242. }
  13243. }
  13244. return BfTypedValue();
  13245. }
  13246. if (useMethodState->mClosureState->mCapturing)
  13247. {
  13248. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  13249. if (thisType->IsValueType())
  13250. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  13251. else
  13252. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  13253. }
  13254. }
  13255. if (mCurMethodInstance == NULL)
  13256. return BfTypedValue();
  13257. auto localDef = useMethodState->mLocals[0];
  13258. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  13259. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  13260. {
  13261. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  13262. {
  13263. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  13264. }
  13265. if (localDef->mIsSplat)
  13266. {
  13267. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  13268. }
  13269. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  13270. }
  13271. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  13272. }
  13273. BfLocalVariable* BfModule::GetThisVariable()
  13274. {
  13275. if (mCurMethodState == NULL)
  13276. return NULL;
  13277. auto methodState = mCurMethodState->GetNonCaptureState();
  13278. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  13279. return methodState->mLocals[0];
  13280. return NULL;
  13281. }
  13282. bool BfModule::IsInGeneric()
  13283. {
  13284. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  13285. }
  13286. bool BfModule::InDefinitionSection()
  13287. {
  13288. if (mCurTypeInstance != NULL)
  13289. {
  13290. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  13291. return false;
  13292. }
  13293. return !IsInSpecializedSection();
  13294. }
  13295. bool BfModule::IsInSpecializedGeneric()
  13296. {
  13297. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  13298. return true;
  13299. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  13300. return false;
  13301. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  13302. }
  13303. bool BfModule::IsInSpecializedSection()
  13304. {
  13305. return IsInSpecializedGeneric() ||
  13306. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  13307. }
  13308. bool BfModule::IsInUnspecializedGeneric()
  13309. {
  13310. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  13311. return true;
  13312. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedType()))
  13313. return true;
  13314. return false;
  13315. }
  13316. //////////////////////////////////////////////////////////////////////////
  13317. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  13318. {
  13319. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  13320. if (type->IsValuelessType())
  13321. return mBfIRBuilder->GetFakeVal();
  13322. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  13323. if ((!doLifetimeEnd) && (WantsLifetimes()))
  13324. {
  13325. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  13326. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  13327. }
  13328. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  13329. auto typeOptions = GetTypeOptions();
  13330. if (typeOptions != NULL)
  13331. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  13332. // Local variable inits are implicitly handled in the Beef Backend
  13333. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  13334. {
  13335. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13336. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13337. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  13338. mBfIRBuilder->ClearDebugLocation(storeInst);
  13339. mBfIRBuilder->SetInsertPoint(prevBlock);
  13340. }
  13341. return allocaInst;
  13342. }
  13343. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  13344. {
  13345. while (localVar->mName.StartsWith('@'))
  13346. {
  13347. localVar->mNamePrefixCount++;
  13348. localVar->mName.Remove(0);
  13349. }
  13350. if (mCurMethodState->mLocals.mAllocSize == 0)
  13351. {
  13352. mCurMethodState->mLocals.Reserve(16);
  13353. mCurMethodState->mLocalVarSet.Reserve(16);
  13354. }
  13355. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  13356. mCurMethodState->mLocals.push_back(localVar);
  13357. BfLocalVarEntry* localVarEntryPtr;
  13358. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  13359. {
  13360. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  13361. localVarEntryPtr->mLocalVar = localVar;
  13362. }
  13363. }
  13364. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13365. {
  13366. if (localVarDef->mResolvedType->IsVar())
  13367. return;
  13368. if ((mBfIRBuilder->DbgHasInfo()) &&
  13369. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  13370. (mHasFullDebugInfo) &&
  13371. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  13372. {
  13373. auto varType = localVarDef->mResolvedType;
  13374. if (localVarDef->mResolvedType->IsValuelessType())
  13375. {
  13376. }
  13377. else
  13378. {
  13379. bool isByAddr = false;
  13380. auto diValue = localVarDef->mValue;
  13381. if (localVarDef->mConstValue)
  13382. diValue = localVarDef->mConstValue;
  13383. else if (localVarDef->mAddr)
  13384. {
  13385. diValue = localVarDef->mAddr;
  13386. isByAddr = true;
  13387. }
  13388. if (diValue.IsConst())
  13389. {
  13390. auto constant = mBfIRBuilder->GetConstant(diValue);
  13391. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  13392. {
  13393. // Ignore for now
  13394. return;
  13395. }
  13396. }
  13397. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  13398. bool didConstToMem = false;
  13399. bool isConstant = false;
  13400. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  13401. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13402. else if (localVarDef->mConstValue)
  13403. {
  13404. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  13405. isConstant =
  13406. (constant->mConstType < BfConstType_GlobalVar) ||
  13407. (constant->mConstType == BfConstType_AggZero) ||
  13408. (constant->mConstType == BfConstType_Agg);
  13409. if (isConstant)
  13410. {
  13411. if (localVarDef->mResolvedType->IsComposite())
  13412. {
  13413. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  13414. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  13415. // if (IsTargetingBeefBackend())
  13416. // {
  13417. // diValue = mBfIRBuilder->CreateAliasValue(constMem);
  13418. // didConstToMem = true;
  13419. //
  13420. // diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13421. // }
  13422. //else
  13423. {
  13424. isByAddr = true;
  13425. mBfIRBuilder->SaveDebugLocation();
  13426. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13427. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13428. mBfIRBuilder->ClearDebugLocation();
  13429. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  13430. auto addrVal = CreateAlloca(ptrType);
  13431. mBfIRBuilder->CreateStore(constMem, addrVal);
  13432. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13433. diValue = addrVal;
  13434. didConstToMem = true;
  13435. mBfIRBuilder->SetInsertPoint(prevBlock);
  13436. mBfIRBuilder->RestoreDebugLocation();
  13437. }
  13438. }
  13439. if (mCompiler->mOptions.IsCodeView())
  13440. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13441. }
  13442. }
  13443. if (!mBfIRBuilder->mIgnoreWrites)
  13444. {
  13445. if ((localVarDef->mIsStatic) && (localVarDef->mAddr) && (!localVarDef->mResolvedType->IsValuelessType()))
  13446. {
  13447. auto refType = CreateRefType(localVarDef->mResolvedType);
  13448. diType = mBfIRBuilder->DbgGetType(refType);
  13449. auto refAlloca = CreateAlloca(refType);
  13450. mBfIRBuilder->CreateStore(localVarDef->mAddr, refAlloca);
  13451. diValue = refAlloca;
  13452. }
  13453. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13454. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  13455. localVarDef->mDbgVarInst = diVariable;
  13456. if (mBfIRBuilder->HasDebugLocation())
  13457. {
  13458. if ((isConstant) && (!didConstToMem))
  13459. {
  13460. BfTypedValue result(localVarDef->mConstValue, localVarDef->mResolvedType);
  13461. FixValueActualization(result);
  13462. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(result.mValue, diVariable);
  13463. }
  13464. else
  13465. {
  13466. if ((IsTargetingBeefBackend()) && (doAliasValue) && (!mIsComptimeModule))
  13467. {
  13468. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  13469. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  13470. }
  13471. if (isByAddr)
  13472. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  13473. else if (diValue)
  13474. {
  13475. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  13476. }
  13477. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  13478. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  13479. }
  13480. }
  13481. }
  13482. }
  13483. }
  13484. }
  13485. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13486. {
  13487. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  13488. {
  13489. if ((!localVarDef->mValue.IsConst()) &&
  13490. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  13491. {
  13492. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  13493. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  13494. }
  13495. }
  13496. if (addDebugInfo)
  13497. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  13498. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  13499. DoAddLocalVariable(localVarDef);
  13500. auto rootMethodState = mCurMethodState->GetRootMethodState();
  13501. if (localVarDef->mLocalVarId == -1)
  13502. {
  13503. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  13504. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  13505. }
  13506. bool checkLocal = true;
  13507. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  13508. {
  13509. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(mCurMethodInstance->mMethodDef->mMethodDeclaration))
  13510. checkLocal = false;
  13511. }
  13512. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!mIsComptimeModule) && (checkLocal))
  13513. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  13514. if (((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL)) && (checkLocal))
  13515. {
  13516. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  13517. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL) && (rootMethodState->mMethodInstance != NULL) && (!mIsComptimeModule))
  13518. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  13519. }
  13520. return localVarDef;
  13521. }
  13522. void BfModule::CreateDIRetVal()
  13523. {
  13524. if (!WantsDebugInfo())
  13525. return;
  13526. /*if (!mCurMethodState->mRetVal)
  13527. {
  13528. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  13529. return;
  13530. }*/
  13531. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  13532. {
  13533. BfType* dbgType = mCurMethodInstance->mReturnType;
  13534. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  13535. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13536. {
  13537. BF_ASSERT(mCurMethodState->mRetValAddr);
  13538. dbgType = CreatePointerType(dbgType);
  13539. dbgValue = mCurMethodState->mRetValAddr;
  13540. }
  13541. else
  13542. {
  13543. BF_ASSERT(!mCurMethodState->mRetValAddr);
  13544. }
  13545. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13546. "@return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  13547. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  13548. }
  13549. }
  13550. BfTypedValue BfModule::CreateTuple(const Array<BfTypedValue>& values, const Array<String>& fieldNames)
  13551. {
  13552. BfTypeVector fieldTypes;
  13553. for (auto arg : values)
  13554. fieldTypes.Add(arg.mType);
  13555. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  13556. auto tupleTypedValue = BfTypedValue(CreateAlloca(tupleType), tupleType, true);
  13557. for (int fieldIdx = 0; fieldIdx < tupleType->mFieldInstances.size(); fieldIdx++)
  13558. {
  13559. auto& fieldInstance = tupleType->mFieldInstances[fieldIdx];
  13560. if (fieldInstance.mDataIdx <= 0)
  13561. continue;
  13562. auto typedVal = values[fieldIdx];
  13563. typedVal = LoadOrAggregateValue(typedVal);
  13564. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, mBfIRBuilder->CreateInBoundsGEP(tupleTypedValue.mValue, 0, fieldInstance.mDataIdx), typedVal.mType->mAlign);
  13565. }
  13566. return tupleTypedValue;
  13567. }
  13568. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  13569. {
  13570. if (variableDef->mName.IsEmpty())
  13571. return;
  13572. BfLocalVarEntry* localVarEntryPtr = NULL;
  13573. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  13574. {
  13575. auto checkLocal = localVarEntryPtr->mLocalVar;
  13576. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  13577. {
  13578. BfError* error;
  13579. if (checkLocal->mIsImplicitParam)
  13580. return; // Ignore 'redefinition'
  13581. if (checkLocal->IsParam())
  13582. {
  13583. if (variableDef->IsParam())
  13584. error = Fail(StrFormat("A parameter named '%s' has already been declared", variableDef->mName.c_str()), variableDef->mNameNode);
  13585. else
  13586. error = Fail(StrFormat("The name '%s' is already used by a parameter. Consider declaring 'var %s;' if you wish to make a mutable copy of that parameter.", variableDef->mName.c_str(), variableDef->mName.c_str()), variableDef->mNameNode);
  13587. }
  13588. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  13589. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13590. else
  13591. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13592. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  13593. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  13594. return;
  13595. }
  13596. }
  13597. }
  13598. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  13599. {
  13600. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  13601. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  13602. {
  13603. if (tokenNode->GetToken() == BfToken_Colon)
  13604. {
  13605. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  13606. {
  13607. Fail("Cannot access method scope across deferred block boundary", scopeName);
  13608. return NULL;
  13609. }
  13610. return &mCurMethodState->mHeadScope;
  13611. }
  13612. else if (tokenNode->GetToken() == BfToken_Mixin)
  13613. {
  13614. if (fromMixinState == NULL)
  13615. {
  13616. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  13617. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  13618. return mCurMethodState->mCurScope;
  13619. }
  13620. fromMixinState->mUsedInvocationScope = true;
  13621. return fromMixinState->mTargetScope;
  13622. }
  13623. else if (tokenNode->GetToken() == BfToken_New)
  13624. return NULL;
  13625. }
  13626. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  13627. {
  13628. auto findLabel = scopeName->ToString();
  13629. bool crossedDeferredBlock = false;
  13630. auto checkScope = mCurMethodState->mCurScope;
  13631. while (checkScope != NULL)
  13632. {
  13633. if (checkScope->mIsDeferredBlock)
  13634. crossedDeferredBlock = true;
  13635. if (checkScope->mLabel == findLabel)
  13636. {
  13637. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  13638. {
  13639. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  13640. return NULL;
  13641. }
  13642. return checkScope;
  13643. }
  13644. checkScope = checkScope->mPrevScope;
  13645. }
  13646. if (!inMixinDecl)
  13647. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  13648. }
  13649. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  13650. {
  13651. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  13652. }
  13653. return mCurMethodState->mCurScope;
  13654. }
  13655. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  13656. {
  13657. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  13658. }
  13659. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  13660. {
  13661. auto scopeData = FindScope(scopeName, false);
  13662. if (scopeData == NULL)
  13663. return NULL;
  13664. int scopeDepth = scopeData->GetDepth();
  13665. // Find the first break data that is at or below the depth of our requested scope
  13666. auto breakData = mCurMethodState->mBreakData;
  13667. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  13668. {
  13669. if (breakData->mScope->mIsConditional)
  13670. return NULL;
  13671. breakData = breakData->mPrevBreakData;
  13672. }
  13673. return breakData;
  13674. }
  13675. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  13676. {
  13677. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  13678. if (!IsTargetingBeefBackend())
  13679. return;
  13680. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  13681. {
  13682. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13683. }
  13684. }
  13685. void BfModule::ClearLifetimeEnds()
  13686. {
  13687. auto scopeData = mCurMethodState->mCurScope;
  13688. while (scopeData != NULL)
  13689. {
  13690. scopeData->mDeferredLifetimeEnds.Clear();
  13691. scopeData = scopeData->mPrevScope;
  13692. }
  13693. }
  13694. bool BfModule::WantsDebugInfo()
  13695. {
  13696. if ((mCurMethodInstance != NULL) &&
  13697. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  13698. return false;
  13699. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  13700. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  13701. }
  13702. BfTypeOptions* BfModule::GetTypeOptions()
  13703. {
  13704. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  13705. return mCurMethodState->mMethodTypeOptions;
  13706. if (mCurMethodInstance == NULL)
  13707. return NULL;
  13708. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  13709. }
  13710. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  13711. {
  13712. BfReflectKind reflectKind = BfReflectKind_None;
  13713. if (attrType->mCustomAttributes != NULL)
  13714. {
  13715. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  13716. {
  13717. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  13718. {
  13719. for (auto& prop : customAttr.mSetProperties)
  13720. {
  13721. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  13722. if (propDef->mName == "ReflectUser")
  13723. {
  13724. if (prop.mParam.mValue.IsConst())
  13725. {
  13726. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  13727. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  13728. }
  13729. }
  13730. }
  13731. // Check for Flags arg
  13732. if (customAttr.mCtorArgs.size() < 2)
  13733. continue;
  13734. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  13735. if (constant == NULL)
  13736. continue;
  13737. if (constant->mTypeCode == BfTypeCode_Boolean)
  13738. continue;
  13739. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  13740. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  13741. }
  13742. }
  13743. }
  13744. return reflectKind;
  13745. }
  13746. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  13747. {
  13748. auto checkTypeInstance = typeInstance;
  13749. while (checkTypeInstance != NULL)
  13750. {
  13751. if (checkTypeInstance->mCustomAttributes != NULL)
  13752. {
  13753. auto checkReflectKind = BfReflectKind_None;
  13754. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  13755. {
  13756. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  13757. {
  13758. if (customAttr.mCtorArgs.size() > 0)
  13759. {
  13760. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  13761. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  13762. }
  13763. else
  13764. {
  13765. checkReflectKind = BfReflectKind_All;
  13766. }
  13767. }
  13768. else
  13769. {
  13770. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  13771. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  13772. }
  13773. }
  13774. if ((checkTypeInstance == typeInstance) ||
  13775. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  13776. {
  13777. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  13778. }
  13779. }
  13780. for (auto ifaceEntry : typeInstance->mInterfaces)
  13781. {
  13782. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  13783. {
  13784. auto iface = ifaceEntry.mInterfaceType;
  13785. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  13786. if (customAttr != NULL)
  13787. {
  13788. for (auto& prop : customAttr->mSetProperties)
  13789. {
  13790. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  13791. if (propDef->mName == "ReflectImplementer")
  13792. {
  13793. if (prop.mParam.mValue.IsConst())
  13794. {
  13795. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  13796. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  13797. }
  13798. }
  13799. }
  13800. }
  13801. }
  13802. }
  13803. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  13804. }
  13805. return reflectKind;
  13806. }
  13807. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  13808. {
  13809. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13810. while (checkScope != NULL)
  13811. {
  13812. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  13813. return true;
  13814. if (checkScope == scope)
  13815. break;
  13816. checkScope = checkScope->mPrevScope;
  13817. }
  13818. return false;
  13819. }
  13820. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  13821. {
  13822. // Is there anything we need to do here?
  13823. if (mBfIRBuilder->mIgnoreWrites)
  13824. {
  13825. // Just visit deferred blocks
  13826. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13827. while (checkScope != NULL)
  13828. {
  13829. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  13830. while (deferredCallEntry != NULL)
  13831. {
  13832. if (deferredCallEntry->mDeferredBlock != NULL)
  13833. {
  13834. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  13835. if (checkScope == &mCurMethodState->mHeadScope)
  13836. CreateRetValLocal();
  13837. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry->mEmitRefNode);
  13838. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  13839. }
  13840. deferredCallEntry = deferredCallEntry->mNext;
  13841. }
  13842. if (checkScope == scopeData)
  13843. break;
  13844. checkScope = checkScope->mPrevScope;
  13845. }
  13846. return;
  13847. }
  13848. // Why did we want to do SetIllegalSrcPos here?
  13849. // Don't we always want to step onto these instances?
  13850. // Find a case where we don't and perhaps only do it there.
  13851. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  13852. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  13853. //SetIllegalSrcPos();
  13854. bool setSrcPos = false;
  13855. bool wantsNop = true;
  13856. BfAstNode* deferCloseNode = NULL;
  13857. if (mCurMethodState->mInPostReturn)
  13858. {
  13859. // These won't get used, they are post-return
  13860. return;
  13861. }
  13862. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  13863. BfScopeData* scopeJumpBlock = NULL;
  13864. bool hadExtraDeferredLifetimeEnds = false;
  13865. auto _FlushLifetimeEnds = [&]()
  13866. {
  13867. for (auto lifetimeEnd : deferredLifetimeEnds)
  13868. {
  13869. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13870. mBfIRBuilder->ClearDebugLocation_Last();
  13871. }
  13872. deferredLifetimeEnds.clear();
  13873. };
  13874. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13875. while (checkScope != NULL)
  13876. {
  13877. if (checkScope->mCloseNode != NULL)
  13878. deferCloseNode = checkScope->mCloseNode;
  13879. if (doneBlock)
  13880. {
  13881. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  13882. for (auto& checkHandler : checkScope->mDeferredHandlers)
  13883. {
  13884. if (checkHandler.mDoneBlock == doneBlock)
  13885. {
  13886. scopeJumpBlock = checkScope;
  13887. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  13888. mBfIRBuilder->ClearDebugLocation_Last();
  13889. _FlushLifetimeEnds();
  13890. break;
  13891. }
  13892. }
  13893. if (scopeJumpBlock != NULL)
  13894. break;
  13895. }
  13896. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  13897. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  13898. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  13899. if (hasWork)
  13900. {
  13901. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  13902. if (deferCloseNode != NULL)
  13903. {
  13904. UpdateSrcPos(deferCloseNode);
  13905. }
  13906. if (checkScope == &mCurMethodState->mHeadScope)
  13907. CreateRetValLocal();
  13908. if (doneBlock)
  13909. {
  13910. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  13911. String blockName = "deferredCalls";
  13912. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  13913. BfDeferredHandler deferredHandler;
  13914. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  13915. {
  13916. mBfIRBuilder->SaveDebugLocation();
  13917. mBfIRBuilder->ClearDebugLocation();
  13918. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  13919. mBfIRBuilder->RestoreDebugLocation();
  13920. }
  13921. else
  13922. {
  13923. // Definitely chain
  13924. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  13925. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  13926. mBfIRBuilder->ClearDebugLocation_Last();
  13927. _FlushLifetimeEnds();
  13928. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  13929. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  13930. }
  13931. deferredHandler.mDoneBlock = doneBlock;
  13932. if (!mBfIRBuilder->mIgnoreWrites)
  13933. checkScope->mDeferredHandlers.push_back(deferredHandler);
  13934. if (checkScope == &mCurMethodState->mHeadScope)
  13935. {
  13936. if (!mCurMethodState->mDIRetVal)
  13937. {
  13938. // Weird case- if we have a return from a mixin, we need the DbgLoc to be for the mixin but we need the DIRetVal to
  13939. // be scoped to the physical method
  13940. /*if (deferCloseNode != NULL)
  13941. {
  13942. UpdateSrcPos(deferCloseNode);
  13943. }*/
  13944. CreateDIRetVal();
  13945. }
  13946. }
  13947. if (checkScope != mCurMethodState->mTailScope)
  13948. {
  13949. if (deferredHandler.mHandlerBlock.IsFake())
  13950. {
  13951. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  13952. }
  13953. if (!mBfIRBuilder->mIgnoreWrites)
  13954. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  13955. }
  13956. }
  13957. HashSet<BfDeferredCallEntry*> handledSet;
  13958. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  13959. while (deferredCallEntry != NULL)
  13960. {
  13961. BfDeferredCallEmitState deferredCallEmitState;
  13962. deferredCallEmitState.mCloseNode = deferCloseNode;
  13963. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  13964. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  13965. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  13966. if (deferCloseNode != NULL)
  13967. {
  13968. UpdateSrcPos(deferCloseNode);
  13969. }
  13970. if (wantsNop)
  13971. EmitEnsureInstructionAt();
  13972. wantsNop = false;
  13973. if (deferredCallEntry->mDeferredBlock != NULL)
  13974. {
  13975. BfDeferredCallEntry** entryPtr = NULL;
  13976. if (!handledSet.TryAdd(deferredCallEntry, &entryPtr))
  13977. {
  13978. // Already handled, can happen if we defer again within the block
  13979. deferredCallEntry = deferredCallEntry->mNext;
  13980. continue;
  13981. }
  13982. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  13983. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  13984. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  13985. {
  13986. // The list changed, start over and ignore anything we've already handled
  13987. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  13988. }
  13989. else
  13990. deferredCallEntry = deferredCallEntry->mNext;
  13991. }
  13992. else
  13993. {
  13994. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  13995. deferredCallEntry = deferredCallEntry->mNext;
  13996. }
  13997. }
  13998. if (checkScope->mSavedStack)
  13999. {
  14000. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  14001. if (mCurMethodState->mDynStackRevIdx)
  14002. {
  14003. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  14004. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  14005. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  14006. }
  14007. }
  14008. }
  14009. if (!checkScope->mIsScopeHead)
  14010. {
  14011. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  14012. if (!IsTargetingBeefBackend())
  14013. {
  14014. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14015. {
  14016. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14017. }
  14018. }
  14019. else
  14020. {
  14021. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14022. {
  14023. deferredLifetimeEnds.Add(lifetimeEnd);
  14024. }
  14025. }
  14026. }
  14027. if (checkScope == scopeData)
  14028. break;
  14029. checkScope = checkScope->mPrevScope;
  14030. }
  14031. if ((doneBlock) && (scopeJumpBlock == NULL))
  14032. {
  14033. mBfIRBuilder->CreateBr(doneBlock);
  14034. mBfIRBuilder->ClearDebugLocation_Last();
  14035. }
  14036. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  14037. // may have been created when other scope lifetimes were available
  14038. _FlushLifetimeEnds();
  14039. // Emit lifetimeEnds after the branch for Beef
  14040. /*if (IsTargetingBeefBackend())
  14041. {
  14042. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  14043. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14044. while (checkScope != NULL)
  14045. {
  14046. if (checkScope == scopeJumpBlock)
  14047. break;
  14048. if (!checkScope->mIsScopeHead)
  14049. {
  14050. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14051. {
  14052. if (needsEnsureInst)
  14053. {
  14054. needsEnsureInst = false;
  14055. }
  14056. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14057. }
  14058. }
  14059. if (checkScope == scopeData)
  14060. break;
  14061. checkScope = checkScope->mPrevScope;
  14062. }
  14063. }*/
  14064. }
  14065. void BfModule::MarkScopeLeft(BfScopeData* scopeData, bool isNoReturn)
  14066. {
  14067. if ((mCurMethodState->mDeferredLocalAssignData != NULL) && (!isNoReturn))
  14068. {
  14069. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  14070. while (deferredLocalAssignData != NULL)
  14071. {
  14072. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  14073. break;
  14074. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  14075. deferredLocalAssignData->mIsUnconditional = false;
  14076. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  14077. }
  14078. }
  14079. // When we leave a scope, mark those as assigned for deferred assignment purposes
  14080. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  14081. {
  14082. auto localDef = mCurMethodState->mLocals[localIdx];
  14083. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  14084. {
  14085. bool hadAssignment = false;
  14086. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  14087. {
  14088. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  14089. if (entry.mLocalVar == localDef)
  14090. hadAssignment = true;
  14091. }
  14092. if (!hadAssignment)
  14093. {
  14094. if (!isNoReturn)
  14095. localDef->mHadExitBeforeAssign = true;
  14096. mCurMethodState->LocalDefined(localDef);
  14097. }
  14098. }
  14099. }
  14100. }
  14101. void BfModule::CreateReturn(BfIRValue val)
  14102. {
  14103. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14104. {
  14105. // Store to sret
  14106. BF_ASSERT(val);
  14107. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14108. mBfIRBuilder->CreateRetVoid();
  14109. return;
  14110. }
  14111. if (mCurMethodInstance->mReturnType->IsVar())
  14112. return;
  14113. if (mCurMethodInstance->mReturnType->IsValuelessType())
  14114. {
  14115. mBfIRBuilder->CreateRetVoid();
  14116. return;
  14117. }
  14118. if (mCurMethodInstance->mReturnType->IsStruct())
  14119. {
  14120. BfTypeCode loweredReturnType = BfTypeCode_None;
  14121. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  14122. if (!mIsComptimeModule)
  14123. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  14124. if (loweredReturnType != BfTypeCode_None)
  14125. {
  14126. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  14127. mBfIRBuilder->CreateStore(val, retVal);
  14128. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  14129. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  14130. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  14131. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  14132. mBfIRBuilder->CreateRet(loadedReturnValue);
  14133. return;
  14134. }
  14135. }
  14136. BF_ASSERT(val);
  14137. mBfIRBuilder->CreateRet(val);
  14138. }
  14139. void BfModule::EmitReturn(const BfTypedValue& val)
  14140. {
  14141. if (mCurMethodState->mIRExitBlock)
  14142. {
  14143. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  14144. {
  14145. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  14146. {
  14147. if ((mCurMethodState->mRetValAddr) || (mCurMethodState->mRetVal))
  14148. {
  14149. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  14150. if (!mCurMethodState->mRetVal)
  14151. retVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetValAddr, mCurMethodInstance->mReturnType->mAlign);
  14152. mBfIRBuilder->CreateAlignedStore(val.mValue, retVal, mCurMethodInstance->mReturnType->mAlign);
  14153. }
  14154. else if (mIsComptimeModule)
  14155. {
  14156. if (!val.mType->IsValuelessType())
  14157. mBfIRBuilder->CreateSetRet(val.mValue, val.mType->mTypeId);
  14158. else
  14159. mBfIRBuilder->CreateSetRet(BfIRValue(), val.mType->mTypeId);
  14160. }
  14161. else
  14162. {
  14163. // Just ignore
  14164. BF_ASSERT(mCurMethodInstance->mReturnType->IsVar());
  14165. }
  14166. }
  14167. }
  14168. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14169. }
  14170. else
  14171. {
  14172. EmitDeferredScopeCalls(false, NULL);
  14173. if (val)
  14174. {
  14175. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14176. }
  14177. }
  14178. mCurMethodState->SetHadReturn(true);
  14179. mCurMethodState->mLeftBlockUncond = true;
  14180. }
  14181. void BfModule::EmitDefaultReturn()
  14182. {
  14183. if (mCurMethodState->mInDeferredBlock)
  14184. return;
  14185. if (mCurMethodState->mIRExitBlock)
  14186. {
  14187. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14188. }
  14189. else
  14190. {
  14191. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mReturnType->IsVar()))
  14192. {
  14193. // Ignore
  14194. }
  14195. else if (mCurMethodInstance->mReturnType->IsVoid())
  14196. mBfIRBuilder->CreateRetVoid();
  14197. else if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == -1))
  14198. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  14199. }
  14200. mCurMethodState->SetHadReturn(true);
  14201. mCurMethodState->mLeftBlockUncond = true;
  14202. }
  14203. void BfModule::AssertErrorState()
  14204. {
  14205. if (mIgnoreErrors)
  14206. return;
  14207. if (mHadBuildError)
  14208. return;
  14209. if (mCurTypeInstance != NULL)
  14210. {
  14211. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  14212. return;
  14213. }
  14214. if (mCurMethodInstance != NULL)
  14215. {
  14216. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  14217. return;
  14218. if (mCurMethodInstance->mHasFailed)
  14219. return;
  14220. }
  14221. // We want the module to be marked as failed even if it's just an error in the parser
  14222. if (mCurMethodInstance != NULL)
  14223. mCurMethodInstance->mHasFailed = true;
  14224. mHadBuildError = true;
  14225. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  14226. if (mCurTypeInstance != NULL)
  14227. {
  14228. if (mCurTypeInstance->mTypeFailed)
  14229. return;
  14230. if ((mCurTypeInstance->mTypeDef->GetDefinition()->mSource != NULL) && (mCurTypeInstance->mTypeDef->GetDefinition()->mSource->mParsingFailed))
  14231. return;
  14232. }
  14233. if (mCurMethodInstance != NULL)
  14234. {
  14235. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) &&
  14236. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14237. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14238. return;
  14239. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) &&
  14240. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14241. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14242. return;
  14243. }
  14244. if (mCompiler->IsAutocomplete())
  14245. return;
  14246. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  14247. }
  14248. void BfModule::AssertParseErrorState()
  14249. {
  14250. if (mCompiler->mRevision == 1)
  14251. AssertErrorState();
  14252. }
  14253. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  14254. {
  14255. BF_ASSERT(delegateType->IsDelegate());
  14256. auto typeInst = delegateType->ToTypeInstance();
  14257. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  14258. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  14259. if (invokeMethodInstance == NULL)
  14260. return GetPrimitiveType(BfTypeCode_Var);
  14261. return invokeMethodInstance->mReturnType;
  14262. }
  14263. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  14264. {
  14265. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  14266. }
  14267. void BfModule::CreateDelegateInvokeMethod()
  14268. {
  14269. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  14270. //mBfIRBuilder->ClearDebugLocation();
  14271. SetIllegalSrcPos();
  14272. auto typeInstance = mCurTypeInstance;
  14273. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  14274. SizedArray<BfIRType, 4> staticParamTypes;
  14275. SizedArray<BfIRValue, 4> staticFuncArgs;
  14276. SizedArray<BfIRValue, 4> memberFuncArgs;
  14277. auto multicastDelegateType = typeInstance->mBaseType;
  14278. if (multicastDelegateType->mFieldInstances.size() != 2)
  14279. {
  14280. AssertErrorState();
  14281. return;
  14282. }
  14283. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  14284. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  14285. auto fieldVal = mBfIRBuilder->CreateAlignedLoad(fieldPtr, mSystem->mPtrSize);
  14286. BfExprEvaluator exprEvaluator(this);
  14287. SizedArray<BfIRType, 8> origParamTypes;
  14288. BfIRType origReturnType;
  14289. BfIRType staticReturnType;
  14290. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  14291. if (mCurMethodInstance->mReturnType->IsValueType())
  14292. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  14293. if ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() != 0))
  14294. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14295. int thisIdx = 0;
  14296. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14297. {
  14298. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  14299. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14300. }
  14301. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14302. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14303. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == 0))
  14304. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14305. mCurMethodInstance->GetIRFunctionInfo(this, staticReturnType, staticParamTypes, true);
  14306. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14307. {
  14308. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  14309. exprEvaluator.PushArg(localVal, staticFuncArgs);
  14310. exprEvaluator.PushArg(localVal, memberFuncArgs);
  14311. }
  14312. auto staticFunc = mBfIRBuilder->CreateFunctionType(staticReturnType, staticParamTypes, false);
  14313. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  14314. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  14315. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  14316. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  14317. auto doneBB = mBfIRBuilder->CreateBlock("done");
  14318. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  14319. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  14320. BfIRValue nonStaticResult;
  14321. BfIRValue staticResult;
  14322. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  14323. /// Non-static invocation
  14324. {
  14325. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  14326. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  14327. mBfIRBuilder->SetInsertPoint(trueBB);
  14328. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  14329. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14330. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  14331. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14332. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  14333. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14334. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  14335. if (callingConv != BfIRCallingConv_CDecl)
  14336. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  14337. mCurMethodState->SetHadReturn(false);
  14338. mCurMethodState->mLeftBlockUncond = false;
  14339. mCurMethodState->mLeftBlockCond = false;
  14340. mBfIRBuilder->CreateBr(doneBB);
  14341. }
  14342. // Static invocation
  14343. {
  14344. mBfIRBuilder->AddBlock(falseBB);
  14345. mBfIRBuilder->SetInsertPoint(falseBB);
  14346. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14347. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  14348. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14349. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  14350. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14351. {
  14352. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  14353. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  14354. }
  14355. // We had a sret for the non-static but no sret for the static (because we have a lowered return type there)
  14356. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1) && (mCurMethodInstance->GetStructRetIdx(true) == -1))
  14357. {
  14358. auto sretToType = mBfIRBuilder->GetPointerTo(staticReturnType);
  14359. auto sretCastedPtr = mBfIRBuilder->CreateBitCast(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), sretToType);
  14360. mBfIRBuilder->CreateStore(staticResult, sretCastedPtr);
  14361. }
  14362. if (callingConv == BfIRCallingConv_ThisCall)
  14363. callingConv = BfIRCallingConv_CDecl;
  14364. if (callingConv != BfIRCallingConv_CDecl)
  14365. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  14366. mCurMethodState->SetHadReturn(false);
  14367. mCurMethodState->mLeftBlockUncond = false;
  14368. mCurMethodState->mLeftBlockCond = false;
  14369. mBfIRBuilder->CreateBr(doneBB);
  14370. }
  14371. mBfIRBuilder->AddBlock(doneBB);
  14372. mBfIRBuilder->SetInsertPoint(doneBB);
  14373. if (mCurMethodInstance->mReturnType->IsVar())
  14374. {
  14375. // Do nothing
  14376. }
  14377. else if ((mCurMethodInstance->mReturnType->IsValuelessType()) ||
  14378. ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1)))
  14379. {
  14380. mBfIRBuilder->CreateRetVoid();
  14381. }
  14382. else
  14383. {
  14384. BfIRType loweredIRReturnType;
  14385. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14386. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14387. if ((!mIsComptimeModule) && (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2)))
  14388. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  14389. else
  14390. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  14391. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  14392. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  14393. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  14394. mBfIRBuilder->CreateRet(phi);
  14395. }
  14396. }
  14397. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  14398. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  14399. {
  14400. auto typeDef = typeInstance->mTypeDef;
  14401. auto methodDeclaration = methodDef->mMethodDeclaration;
  14402. if (!mCompiler->mIsResolveOnly)
  14403. return true;
  14404. if (typeInstance->IsGenericTypeInstance())
  14405. {
  14406. // We only really want to process the unspecialized type for autocompletion
  14407. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  14408. return false;
  14409. }
  14410. BfAstNode* checkNode = methodDeclaration;
  14411. if (methodDeclaration == NULL)
  14412. checkNode = methodDef->mBody;
  14413. if ((!mCompiler->mResolvePassData->mParsers.IsEmpty()) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParsers[0])))
  14414. {
  14415. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  14416. return true;
  14417. }
  14418. return false;
  14419. }
  14420. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  14421. {
  14422. methodInst->mAppendAllocAlign = 1;
  14423. }
  14424. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args, bool force)
  14425. {
  14426. BP_ZONE("BfModule::TryConstCalcAppend");
  14427. BF_ASSERT(methodInst->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  14428. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (!force))
  14429. return BfTypedValue();
  14430. // We want to regenerate all ctor calls when the method internals change
  14431. {
  14432. auto checkTypeInst = methodInst->GetOwner();
  14433. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  14434. {
  14435. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  14436. checkTypeInst = GetBaseType(checkTypeInst);
  14437. }
  14438. }
  14439. if (!methodInst->mMayBeConst)
  14440. return BfTypedValue();
  14441. // Do we need to iterate in order to resolve mAppendAllocAlign?
  14442. bool isFirstRun = methodInst->mEndingAppendAllocAlign < 0;
  14443. bool wasAllConst = true;
  14444. int argIdx = 0;
  14445. int paramIdx = 0;
  14446. while (true)
  14447. {
  14448. if (argIdx >= (int)args.size())
  14449. break;
  14450. auto paramType = methodInst->GetParamType(paramIdx);
  14451. PopulateType(paramType);
  14452. int argCount = 0;
  14453. if (!paramType->IsValuelessType())
  14454. {
  14455. if ((!mIsComptimeModule) && (methodInst->GetParamIsSplat(paramIdx)))
  14456. argCount = paramType->GetSplatCount();
  14457. else
  14458. argCount = 1;
  14459. for (int argOfs = 0; argOfs < argCount; argOfs++)
  14460. {
  14461. auto arg = args[argIdx + argOfs];
  14462. if (!arg.IsConst())
  14463. {
  14464. wasAllConst = false;
  14465. if (!isFirstRun)
  14466. {
  14467. auto& param = methodInst->mParams[argIdx];
  14468. if (param.mReferencedInConstPass)
  14469. {
  14470. // If this param is required as part of the const calculation then
  14471. // we require that it be const...
  14472. return BfTypedValue();
  14473. }
  14474. }
  14475. }
  14476. }
  14477. }
  14478. paramIdx++;
  14479. argIdx += argCount;
  14480. }
  14481. auto methodDef = methodInst->mMethodDef;
  14482. auto methodDecl = methodDef->GetMethodDeclaration();
  14483. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14484. if (methodDeclBlock == NULL)
  14485. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  14486. BfTypedValue constValue;
  14487. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  14488. auto checkState = mCurMethodState->mConstResolveState;
  14489. while (checkState != NULL)
  14490. {
  14491. if (checkState->mMethodInstance == methodInst)
  14492. {
  14493. return BfTypedValue();
  14494. }
  14495. checkState = checkState->mPrevConstResolveState;
  14496. }
  14497. //auto accumValue = GetConstValue(0);
  14498. bool failed = false;
  14499. //
  14500. {
  14501. BfConstResolveState constResolveState;
  14502. constResolveState.mMethodInstance = methodInst;
  14503. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  14504. constResolveState.mInCalcAppend = true;
  14505. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14506. BfMethodState methodState;
  14507. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  14508. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  14509. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  14510. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  14511. methodState.mConstResolveState = &constResolveState;
  14512. int argIdx = 0;
  14513. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14514. {
  14515. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  14516. continue;
  14517. auto paramType = methodInst->GetParamType(paramIdx);
  14518. // Fix this after we allow structs to be consts
  14519. //BF_ASSERT(!paramType->IsSplattable());
  14520. BfLocalVariable* localVar = new BfLocalVariable();
  14521. localVar->mName = methodInst->GetParamName(paramIdx);
  14522. localVar->mResolvedType = paramType;
  14523. localVar->mConstValue = args[argIdx];
  14524. localVar->mParamIdx = paramIdx;
  14525. AddLocalVariableDef(localVar);
  14526. argIdx++;
  14527. }
  14528. AppendAllocVisitor appendAllocVisitor;
  14529. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  14530. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  14531. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  14532. if (baseCtorAppendValue)
  14533. {
  14534. if (baseCtorAppendValue.mValue.IsFake())
  14535. appendAllocVisitor.mFailed = true;
  14536. else
  14537. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  14538. }
  14539. appendAllocVisitor.mModule = this;
  14540. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14541. if (constResolveState.mFailed)
  14542. appendAllocVisitor.mFailed = true;
  14543. if (!appendAllocVisitor.mFailed)
  14544. constValue = appendAllocVisitor.mConstAccum;
  14545. if (isFirstRun)
  14546. {
  14547. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  14548. if (mCurMethodInstance->mAppendAllocAlign <= 0)
  14549. mCurMethodInstance->mAppendAllocAlign = 1;
  14550. }
  14551. if (isFirstRun)
  14552. {
  14553. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14554. {
  14555. auto localVar = mCurMethodState->mLocals[paramIdx];
  14556. if (localVar->mReadFromId != -1)
  14557. {
  14558. auto& param = methodInst->mParams[paramIdx];
  14559. param.mReferencedInConstPass = true;
  14560. }
  14561. }
  14562. }
  14563. }
  14564. mBfIRBuilder->SetInsertPoint(prevBlock);
  14565. if (!constValue)
  14566. {
  14567. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  14568. // all-const args
  14569. if (wasAllConst)
  14570. {
  14571. methodInst->mMayBeConst = false;
  14572. }
  14573. }
  14574. return constValue;
  14575. }
  14576. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  14577. {
  14578. // Any errors should only be shown in the actual CTOR call
  14579. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  14580. auto methodDef = mCurMethodInstance->mMethodDef;
  14581. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  14582. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  14583. BfCustomAttributes* customAttributes = NULL;
  14584. defer(delete customAttributes);
  14585. BfInvocationExpression* ctorInvocation = NULL;
  14586. if (ctorDeclaration != NULL)
  14587. {
  14588. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  14589. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  14590. {
  14591. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  14592. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  14593. }
  14594. }
  14595. BfTypeInstance* targetType = NULL;
  14596. if (ctorInvocation != NULL)
  14597. {
  14598. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  14599. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  14600. }
  14601. else
  14602. targetType = mCurTypeInstance->mBaseType;
  14603. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  14604. return NULL;
  14605. auto targetRefNode = methodDef->GetRefNode();
  14606. BfType* targetThisType = targetType;
  14607. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  14608. BfExprEvaluator exprEvaluator(this);
  14609. BfResolvedArgs argValues;
  14610. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  14611. {
  14612. argValues.Init(&ctorInvocation->mArguments);
  14613. }
  14614. //
  14615. {
  14616. }
  14617. BfFunctionBindResult bindResult;
  14618. bindResult.mSkipThis = true;
  14619. bindResult.mWantsArgs = true;
  14620. {
  14621. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14622. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14623. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14624. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  14625. }
  14626. if (bindResult.mMethodInstance == NULL)
  14627. {
  14628. AssertErrorState();
  14629. return BfTypedValue();
  14630. }
  14631. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  14632. {
  14633. return BfTypedValue();
  14634. }
  14635. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14636. bindResult.mIRArgs.RemoveAt(0);
  14637. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  14638. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs, true);
  14639. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  14640. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  14641. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  14642. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  14643. if (appendSizeTypedValue)
  14644. return appendSizeTypedValue;
  14645. if (constOnly)
  14646. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  14647. bool needsRecalc = false;
  14648. for (auto irArg : bindResult.mIRArgs)
  14649. {
  14650. if (irArg.IsFake())
  14651. needsRecalc = true;
  14652. }
  14653. auto calcAppendArgs = bindResult.mIRArgs;
  14654. if (needsRecalc)
  14655. {
  14656. // Do it again, but without mIgnoreWrites set
  14657. BfResolvedArgs argValues;
  14658. argValues.Init(&ctorInvocation->mArguments);
  14659. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14660. BfFunctionBindResult bindResult;
  14661. bindResult.mSkipThis = true;
  14662. bindResult.mWantsArgs = true;
  14663. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14664. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  14665. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14666. bindResult.mIRArgs.RemoveAt(0);
  14667. calcAppendArgs = bindResult.mIRArgs;
  14668. }
  14669. if (mBfIRBuilder->mIgnoreWrites)
  14670. {
  14671. appendSizeTypedValue = GetFakeTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  14672. }
  14673. else
  14674. {
  14675. BF_ASSERT(calcAppendMethodModule.mFunc);
  14676. appendSizeTypedValue = exprEvaluator.CreateCall(NULL, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  14677. }
  14678. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  14679. return appendSizeTypedValue;
  14680. }
  14681. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  14682. void BfModule::EmitCtorCalcAppend()
  14683. {
  14684. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  14685. return;
  14686. auto methodDef = mCurMethodInstance->mMethodDef;
  14687. auto methodDecl = methodDef->GetMethodDeclaration();
  14688. Array<BfAstNode*> deferredNodeList;
  14689. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14690. if (methodDeclBlock == NULL)
  14691. return;
  14692. AppendAllocVisitor appendAllocVisitor;
  14693. auto baseCalcAppend = CallBaseCtorCalc(false);
  14694. if (baseCalcAppend)
  14695. {
  14696. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  14697. }
  14698. appendAllocVisitor.mModule = this;
  14699. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14700. }
  14701. void BfModule::CreateStaticCtor()
  14702. {
  14703. auto typeDef = mCurTypeInstance->mTypeDef;
  14704. auto methodDef = mCurMethodInstance->mMethodDef;
  14705. BfIRBlock exitBB;
  14706. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  14707. {
  14708. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  14709. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  14710. mBfIRBuilder->MapType(boolType),
  14711. false,
  14712. BfIRLinkageType_Internal,
  14713. GetDefaultValue(boolType),
  14714. "didStaticInit");
  14715. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  14716. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14717. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  14718. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  14719. mBfIRBuilder->SetInsertPoint(initBB);
  14720. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  14721. }
  14722. // Do DLL imports
  14723. if (!mDllImportEntries.empty())
  14724. {
  14725. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  14726. PopulateType(internalType);
  14727. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  14728. if (!getSharedProcAddressInstance)
  14729. {
  14730. if (!mCompiler->mPassInstance->HasFailed())
  14731. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  14732. }
  14733. }
  14734. // Fill in initializer values
  14735. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  14736. {
  14737. for (auto fieldDef : typeDef->mFields)
  14738. {
  14739. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic))
  14740. {
  14741. // For extensions, only handle these fields in the appropriate extension
  14742. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14743. continue;
  14744. auto initializer = fieldDef->GetInitializer();
  14745. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  14746. if (!fieldInst->mFieldIncluded)
  14747. continue;
  14748. if (fieldInst->mResolvedType->IsVar())
  14749. {
  14750. continue;
  14751. }
  14752. if (fieldInst->IsAppendedObject())
  14753. {
  14754. AppendedObjectInit(fieldInst);
  14755. }
  14756. else if (initializer != NULL)
  14757. {
  14758. UpdateSrcPos(initializer);
  14759. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  14760. }
  14761. }
  14762. }
  14763. auto _CheckInitBlock = [&](BfAstNode* node)
  14764. {
  14765. };
  14766. EmitInitBlocks(_CheckInitBlock);
  14767. }
  14768. else
  14769. {
  14770. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  14771. {
  14772. if (tempTypeDef->mFullName == typeDef->mFullName)
  14773. {
  14774. for (auto fieldDef : tempTypeDef->mFields)
  14775. {
  14776. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  14777. {
  14778. if (fieldDef->GetInitializer() != NULL)
  14779. {
  14780. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDef->GetInitializer()))
  14781. {
  14782. sourceClassifier->SetElementType(fieldDef->GetInitializer(), BfSourceElementType_Normal);
  14783. sourceClassifier->VisitChildNoRef(fieldDef->GetInitializer());
  14784. }
  14785. BfType* wantType = NULL;
  14786. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  14787. {
  14788. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  14789. }
  14790. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  14791. if (fieldDef->mIsAppend)
  14792. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  14793. CreateValueFromExpression(fieldDef->GetInitializer(), wantType, exprFlags);
  14794. }
  14795. }
  14796. }
  14797. }
  14798. }
  14799. }
  14800. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14801. CallChainedMethods(mCurMethodInstance, false);
  14802. }
  14803. void BfModule::EmitDtorBody()
  14804. {
  14805. if (!mCurMethodState->mIRExitBlock)
  14806. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14807. if (mCurTypeInstance->IsClosure())
  14808. {
  14809. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  14810. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  14811. auto thisVal = GetThis();
  14812. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  14813. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  14814. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  14815. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  14816. SizedArray<BfIRValue, 1> args;
  14817. args.push_back(thisVal.mValue);
  14818. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  14819. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  14820. // Fall through to Object::~this call
  14821. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  14822. if (mIsComptimeModule)
  14823. mCompiler->mCeMachine->QueueMethod(dtorFunc.mMethodInstance, dtorFunc.mFunc);
  14824. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  14825. SizedArray<BfIRValue, 1> vals = { basePtr };
  14826. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  14827. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  14828. mBfIRBuilder->SetTailCall(result);
  14829. return;
  14830. }
  14831. auto typeDef = mCurTypeInstance->mTypeDef;
  14832. auto methodDef = mCurMethodInstance->mMethodDef;
  14833. auto methodDeclaration = methodDef->GetMethodDeclaration();
  14834. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14835. CallChainedMethods(mCurMethodInstance, true);
  14836. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14837. {
  14838. VisitEmbeddedStatement(bodyBlock);
  14839. if (bodyBlock->mCloseBrace != NULL)
  14840. {
  14841. UpdateSrcPos(bodyBlock->mCloseBrace);
  14842. }
  14843. }
  14844. else
  14845. {
  14846. if (methodDeclaration != NULL)
  14847. UpdateSrcPos(methodDeclaration);
  14848. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  14849. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  14850. else if (typeDef->mTypeDeclaration != NULL)
  14851. UpdateSrcPos(typeDef->mTypeDeclaration);
  14852. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  14853. {
  14854. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  14855. }
  14856. }
  14857. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  14858. {
  14859. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  14860. {
  14861. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  14862. auto fieldDef = fieldInst->GetFieldDef();
  14863. BfFieldDeclaration* fieldDecl = NULL;
  14864. if (fieldDef != NULL)
  14865. fieldDecl = fieldDef->GetFieldDeclaration();
  14866. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDecl != NULL) && (fieldDecl->mFieldDtor != NULL))
  14867. {
  14868. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  14869. {
  14870. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  14871. continue;
  14872. }
  14873. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  14874. {
  14875. Fail("Structs cannot have field destructors", fieldDecl->mFieldDtor->mTildeToken, true);
  14876. }
  14877. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  14878. auto fieldDtor = fieldDecl->mFieldDtor;
  14879. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  14880. continue;
  14881. UpdateSrcPos(fieldDtor);
  14882. BfScopeData scopeData;
  14883. mCurMethodState->AddScope(&scopeData);
  14884. NewScopeState();
  14885. UpdateSrcPos(fieldDtor);
  14886. bool hasDbgInfo = (!fieldDef->mIsConst);
  14887. if (hasDbgInfo)
  14888. {
  14889. mBfIRBuilder->SaveDebugLocation();
  14890. mBfIRBuilder->ClearDebugLocation();
  14891. }
  14892. BfIRValue value;
  14893. if (fieldDef->mIsStatic)
  14894. {
  14895. value = ReferenceStaticField(fieldInst).mValue;
  14896. }
  14897. else
  14898. {
  14899. PopulateType(fieldInst->mResolvedType);
  14900. if (fieldInst->mResolvedType->IsValuelessType())
  14901. {
  14902. value = mBfIRBuilder->GetFakeVal();
  14903. }
  14904. else if (!mCurTypeInstance->IsValueType())
  14905. {
  14906. auto thisValue = GetThis();
  14907. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  14908. }
  14909. else
  14910. {
  14911. AssertErrorState();
  14912. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  14913. }
  14914. }
  14915. BfIRValue staticVal;
  14916. if (hasDbgInfo)
  14917. {
  14918. BfIRValue dbgShowValue = value;
  14919. BfLocalVariable* localDef = new BfLocalVariable();
  14920. localDef->mName = "_";
  14921. localDef->mResolvedType = fieldInst->mResolvedType;
  14922. if (fieldInst->IsAppendedObject())
  14923. {
  14924. localDef->mValue = mBfIRBuilder->CreateBitCast(value, mBfIRBuilder->MapType(fieldInst->mResolvedType));
  14925. }
  14926. else
  14927. {
  14928. localDef->mAddr = value;
  14929. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  14930. {
  14931. // Create another pointer indirection, a ref to the gep
  14932. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  14933. auto allocaInst = CreateAlloca(refFieldType);
  14934. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  14935. localDef->mResolvedType = refFieldType;
  14936. localDef->mAddr = allocaInst;
  14937. }
  14938. }
  14939. mBfIRBuilder->RestoreDebugLocation();
  14940. auto defLocalVar = AddLocalVariableDef(localDef, true);
  14941. if (!fieldInst->IsAppendedObject())
  14942. {
  14943. // Put back so we actually modify the correct value*/
  14944. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  14945. defLocalVar->mAddr = value;
  14946. }
  14947. }
  14948. while (fieldDtor != NULL)
  14949. {
  14950. if (mCompiler->mResolvePassData != NULL)
  14951. {
  14952. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  14953. {
  14954. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  14955. sourceClassifier->VisitChild(fieldDtor);
  14956. }
  14957. }
  14958. UpdateSrcPos(fieldDtor);
  14959. VisitEmbeddedStatement(fieldDtor->mBody);
  14960. fieldDtor = fieldDtor->mNextFieldDtor;
  14961. }
  14962. RestoreScopeState();
  14963. }
  14964. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldInst->IsAppendedObject()))
  14965. {
  14966. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  14967. {
  14968. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  14969. continue;
  14970. }
  14971. auto refNode = fieldDef->GetRefNode();
  14972. UpdateSrcPos(refNode);
  14973. auto objectType = mContext->mBfObjectType;
  14974. BfTypeInstance* checkTypeInst = mCurTypeInstance->ToTypeInstance();
  14975. BfTypedValue val;
  14976. if (fieldDef->mIsStatic)
  14977. val = ReferenceStaticField(fieldInst);
  14978. else
  14979. {
  14980. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  14981. val = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  14982. }
  14983. bool allowPrivate = checkTypeInst == mCurTypeInstance;
  14984. bool allowProtected = allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst);
  14985. while (checkTypeInst != NULL)
  14986. {
  14987. auto dtorMethodDef = checkTypeInst->mTypeDef->GetMethodByName("~this");
  14988. if (dtorMethodDef)
  14989. {
  14990. if (!CheckProtection(dtorMethodDef->mProtection, checkTypeInst->mTypeDef, allowProtected, allowPrivate))
  14991. {
  14992. auto error = Fail(StrFormat("'%s.~this()' is inaccessible due to its protection level", TypeToString(checkTypeInst).c_str()), refNode); // CS0122
  14993. }
  14994. }
  14995. checkTypeInst = checkTypeInst->mBaseType;
  14996. allowPrivate = false;
  14997. }
  14998. // call dtor
  14999. BfExprEvaluator expressionEvaluator(this);
  15000. PopulateType(val.mType);
  15001. PopulateType(objectType, BfPopulateType_DataAndMethods);
  15002. if (objectType->mVirtualMethodTable.size() == 0)
  15003. {
  15004. if (!mCompiler->IsAutocomplete())
  15005. AssertErrorState();
  15006. }
  15007. else if (!IsSkippingExtraResolveChecks())
  15008. {
  15009. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  15010. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  15011. SizedArray<BfIRValue, 4> llvmArgs;
  15012. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  15013. expressionEvaluator.CreateCall(refNode, methodInstance, mBfIRBuilder->GetFakeVal(), false, llvmArgs);
  15014. }
  15015. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  15016. {
  15017. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  15018. auto int8PtrVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(int8PtrType));
  15019. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  15020. }
  15021. }
  15022. }
  15023. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15024. {
  15025. auto checkBaseType = mCurTypeInstance->mBaseType;
  15026. while (checkBaseType != NULL)
  15027. {
  15028. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15029. {
  15030. if (bodyBlock->mCloseBrace != NULL)
  15031. UpdateSrcPos(bodyBlock->mCloseBrace);
  15032. }
  15033. else
  15034. {
  15035. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  15036. }
  15037. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  15038. if (dtorMethodDef != NULL)
  15039. {
  15040. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  15041. if (IsSkippingExtraResolveChecks())
  15042. {
  15043. // Nothing
  15044. }
  15045. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  15046. {
  15047. if ((!IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  15048. {
  15049. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  15050. SizedArray<BfIRValue, 1> vals = { basePtr };
  15051. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  15052. if (mIsComptimeModule)
  15053. mCompiler->mCeMachine->QueueMethod(dtorMethodInstance.mMethodInstance, dtorMethodInstance.mFunc);
  15054. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  15055. }
  15056. }
  15057. else
  15058. {
  15059. // Invalid base dtor declaration
  15060. AssertErrorState();
  15061. }
  15062. break;
  15063. }
  15064. checkBaseType = checkBaseType->mBaseType;
  15065. }
  15066. }
  15067. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15068. }
  15069. else
  15070. {
  15071. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15072. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15073. // resolve pass, NOT the autocomplete expression
  15074. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15075. {
  15076. if (tempTypeDef->mFullName == typeDef->mFullName)
  15077. {
  15078. for (auto fieldDef : tempTypeDef->mFields)
  15079. {
  15080. auto fieldDecl = fieldDef->GetFieldDeclaration();
  15081. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  15082. (fieldDecl->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  15083. {
  15084. BfType* fieldType = NULL;
  15085. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  15086. {
  15087. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  15088. auto curFieldDef = curFieldInstance->GetFieldDef();
  15089. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  15090. fieldType = curFieldInstance->GetResolvedType();
  15091. }
  15092. if (fieldType == NULL)
  15093. fieldType = GetPrimitiveType(BfTypeCode_Var);
  15094. auto fieldDtor = fieldDecl->mFieldDtor;
  15095. BfScopeData scopeData;
  15096. mCurMethodState->AddScope(&scopeData);
  15097. NewScopeState();
  15098. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  15099. if (fieldType != NULL)
  15100. {
  15101. BfLocalVariable* localDef = new BfLocalVariable();
  15102. localDef->mName = "_";
  15103. localDef->mResolvedType = fieldType;
  15104. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  15105. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15106. AddLocalVariableDef(localDef);
  15107. }
  15108. while (fieldDtor != NULL)
  15109. {
  15110. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15111. {
  15112. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15113. sourceClassifier->VisitChild(fieldDtor);
  15114. }
  15115. UpdateSrcPos(fieldDtor);
  15116. VisitEmbeddedStatement(fieldDtor->mBody);
  15117. fieldDtor = fieldDtor->mNextFieldDtor;
  15118. }
  15119. RestoreScopeState();
  15120. }
  15121. }
  15122. }
  15123. }
  15124. }
  15125. }
  15126. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  15127. {
  15128. BF_ASSERT(methodInstance->mIsReified);
  15129. auto typeInstance = methodInstance->GetOwner();
  15130. bool foundDllImportAttr = false;
  15131. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  15132. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  15133. {
  15134. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  15135. {
  15136. foundDllImportAttr = true;
  15137. }
  15138. }
  15139. if (!foundDllImportAttr)
  15140. {
  15141. AssertErrorState();
  15142. return BfIRValue();
  15143. }
  15144. StringT<512> name = "bf_hs_preserve@";
  15145. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  15146. name += "__imp";
  15147. BfIRType returnType;
  15148. SizedArray<BfIRType, 8> paramTypes;
  15149. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  15150. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  15151. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  15152. BfIRValue initVal;
  15153. if (define)
  15154. {
  15155. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  15156. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  15157. }
  15158. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  15159. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  15160. {
  15161. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15162. auto ptrType = CreatePointerType(voidType);
  15163. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  15164. }
  15165. return globalVar;
  15166. }
  15167. void BfModule::CreateDllImportMethod()
  15168. {
  15169. if (mBfIRBuilder->mIgnoreWrites)
  15170. return;
  15171. auto globalVar = mFuncReferences[mCurMethodInstance];
  15172. if (!globalVar)
  15173. return;
  15174. bool allowTailCall = true;
  15175. mBfIRBuilder->ClearDebugLocation();
  15176. bool isHotCompile = mCompiler->IsHotCompile();
  15177. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  15178. if (isHotCompile)
  15179. {
  15180. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  15181. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  15182. }
  15183. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  15184. BfIRType returnType;
  15185. SizedArray<BfIRType, 8> paramTypes;
  15186. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15187. SizedArray<BfIRValue, 8> args;
  15188. for (int i = 0; i < (int)paramTypes.size(); i++)
  15189. args.push_back(mBfIRBuilder->GetArgument(i));
  15190. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15191. if (isHotCompile)
  15192. {
  15193. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  15194. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  15195. if (callingConvention == BfIRCallingConv_StdCall)
  15196. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  15197. else if (callingConvention == BfIRCallingConv_FastCall)
  15198. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  15199. else
  15200. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15201. if (allowTailCall)
  15202. mBfIRBuilder->SetTailCall(result);
  15203. CreateReturn(result);
  15204. mCurMethodState->mHadReturn = true;
  15205. }
  15206. if (HasCompiledOutput())
  15207. {
  15208. BfDllImportEntry dllImportEntry;
  15209. dllImportEntry.mFuncVar = globalVar;
  15210. dllImportEntry.mMethodInstance = mCurMethodInstance;
  15211. mDllImportEntries.push_back(dllImportEntry);
  15212. }
  15213. }
  15214. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  15215. {
  15216. auto methodDef = methodInstance->mMethodDef;
  15217. BfTypeInstance* owner = NULL;
  15218. if (!methodDef->mIsStatic)
  15219. owner = methodInstance->GetThisType()->ToTypeInstance();
  15220. if (owner == NULL)
  15221. owner = methodInstance->GetOwner();
  15222. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  15223. return BfIRCallingConv_CDecl;
  15224. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  15225. return BfIRCallingConv_StdCall;
  15226. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  15227. return BfIRCallingConv_FastCall;
  15228. if (!methodDef->mIsStatic)
  15229. {
  15230. if (owner->mIsCRepr)
  15231. return BfIRCallingConv_ThisCall;
  15232. if ((!owner->IsValuelessType()) &&
  15233. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  15234. return BfIRCallingConv_ThisCall;
  15235. }
  15236. return BfIRCallingConv_CDecl;
  15237. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  15238. }
  15239. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  15240. {
  15241. BfMethodDef* methodDef = NULL;
  15242. if (methodInstance != NULL)
  15243. methodDef = methodInstance->mMethodDef;
  15244. if (!func)
  15245. return;
  15246. if (mCompiler->mOptions.mNoFramePointerElim)
  15247. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  15248. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  15249. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  15250. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  15251. if (methodInstance == NULL)
  15252. return;
  15253. if (methodInstance->mReturnType->IsVar())
  15254. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_VarRet);
  15255. if (methodDef->mImportKind == BfImportKind_Export)
  15256. {
  15257. if (methodDef->mDeclaringType->mProject->mTargetType != BfTargetType_BeefLib_StaticLib)
  15258. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  15259. }
  15260. if (methodDef->mIsNoReturn)
  15261. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  15262. auto callingConv = GetIRCallingConvention(methodInstance);
  15263. if (callingConv != BfIRCallingConv_CDecl)
  15264. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  15265. if (isInlined)
  15266. {
  15267. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15268. }
  15269. int argIdx = 0;
  15270. int paramIdx = 0;
  15271. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  15272. paramIdx = -1;
  15273. int argCount = methodInstance->GetIRFunctionParamCount(this);
  15274. while (argIdx < argCount)
  15275. {
  15276. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  15277. {
  15278. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  15279. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  15280. argIdx++;
  15281. continue;
  15282. }
  15283. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  15284. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  15285. paramIdx++;
  15286. BfType* resolvedTypeRef = NULL;
  15287. BfType* resolvedTypeRef2 = NULL;
  15288. String paramName;
  15289. bool isSplattable = false;
  15290. bool tryLowering = !mIsComptimeModule;
  15291. if (isThis)
  15292. {
  15293. paramName = "this";
  15294. if (methodInstance->mIsClosure)
  15295. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  15296. else
  15297. resolvedTypeRef = methodInstance->GetThisType();
  15298. isSplattable = (!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(-1));
  15299. tryLowering = (!mIsComptimeModule) && (methodInstance->AllowsSplatting(-1));
  15300. }
  15301. else
  15302. {
  15303. paramName = methodInstance->GetParamName(paramIdx);
  15304. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  15305. if (resolvedTypeRef->IsMethodRef())
  15306. isSplattable = true;
  15307. else if ((!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(paramIdx)))
  15308. {
  15309. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15310. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15311. {
  15312. // crepr splat is always splattable
  15313. isSplattable = true;
  15314. }
  15315. else
  15316. {
  15317. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15318. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15319. isSplattable = true;
  15320. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  15321. isSplattable = true;
  15322. }
  15323. }
  15324. }
  15325. if (tryLowering)
  15326. {
  15327. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15328. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15329. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  15330. {
  15331. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  15332. argIdx++;
  15333. if (loweredTypeCode2 != BfTypeCode_None)
  15334. {
  15335. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  15336. argIdx++;
  15337. }
  15338. paramIdx++;
  15339. continue;
  15340. }
  15341. }
  15342. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  15343. {
  15344. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  15345. int addDeref = -1;
  15346. if (resolvedTypeRef->IsRef())
  15347. {
  15348. auto refType = (BfRefType*)resolvedTypeRef;
  15349. auto elementType = refType->mElementType;
  15350. PopulateType(elementType, BfPopulateType_Data);
  15351. addDeref = elementType->mSize;
  15352. if ((addDeref <= 0) && (!elementType->IsValuelessType()) && (!elementType->IsOpaque()))
  15353. AssertErrorState();
  15354. }
  15355. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  15356. {
  15357. if (isThis)
  15358. {
  15359. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  15360. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  15361. addDeref = resolvedTypeRef->mSize;
  15362. }
  15363. else if (methodInstance->WantsStructsAttribByVal(resolvedTypeRef))
  15364. {
  15365. mBfIRBuilder->PopulateType(resolvedTypeRef, BfIRPopulateType_Full);
  15366. BF_ASSERT(resolvedTypeRef->mAlign > 0);
  15367. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  15368. }
  15369. }
  15370. else if (resolvedTypeRef->IsPrimitiveType())
  15371. {
  15372. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  15373. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  15374. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  15375. }
  15376. if (addDeref >= 0)
  15377. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  15378. argIdx++;
  15379. };
  15380. if (isSplattable)
  15381. {
  15382. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  15383. {
  15384. if (checkType->IsStruct())
  15385. {
  15386. auto checkTypeInstance = checkType->ToTypeInstance();
  15387. if (checkTypeInstance->mBaseType != NULL)
  15388. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  15389. if (checkTypeInstance->mIsUnion)
  15390. {
  15391. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  15392. checkTypeLambda(unionInnerType, curName + "_data");
  15393. }
  15394. else
  15395. {
  15396. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  15397. {
  15398. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  15399. auto fieldDef = fieldInstance->GetFieldDef();
  15400. if (fieldInstance->mDataIdx >= 0)
  15401. {
  15402. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  15403. }
  15404. }
  15405. }
  15406. if (checkTypeInstance->IsEnum())
  15407. {
  15408. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  15409. argIdx++;
  15410. }
  15411. }
  15412. else if (checkType->IsMethodRef())
  15413. {
  15414. auto methodRefType = (BfMethodRefType*)checkType;
  15415. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  15416. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  15417. {
  15418. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  15419. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  15420. {
  15421. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  15422. }
  15423. else
  15424. {
  15425. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  15426. }
  15427. }
  15428. }
  15429. else if (!checkType->IsValuelessType())
  15430. {
  15431. _SetupParam(curName, checkType);
  15432. }
  15433. };
  15434. checkTypeLambda(resolvedTypeRef, paramName);
  15435. paramIdx++;
  15436. continue;
  15437. }
  15438. _SetupParam(paramName, resolvedTypeRef);
  15439. if (resolvedTypeRef2 != NULL)
  15440. _SetupParam(paramName, resolvedTypeRef2);
  15441. paramIdx++;
  15442. }
  15443. }
  15444. void BfModule::EmitInitBlocks(const std::function<void(BfAstNode*)>& initBlockCallback)
  15445. {
  15446. auto methodDef = mCurMethodInstance->mMethodDef;
  15447. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  15448. BfMemberSetEntry* entry = NULL;
  15449. BfMethodDef* initMethodDef = NULL;
  15450. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  15451. if (entry != NULL)
  15452. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  15453. SizedArray<BfAstNode*, 8> initBodies;
  15454. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  15455. {
  15456. if (initMethodDef->mDeclaringType->GetDefinition() != methodDef->mDeclaringType->GetDefinition())
  15457. continue;
  15458. if (initMethodDef->mMethodType != BfMethodType_Init)
  15459. continue;
  15460. if (initMethodDef->mIsStatic != methodDef->mIsStatic)
  15461. continue;
  15462. initBodies.Insert(0, initMethodDef->mBody);
  15463. }
  15464. for (auto body : initBodies)
  15465. {
  15466. initBlockCallback(body);
  15467. VisitEmbeddedStatement(body);
  15468. }
  15469. }
  15470. void BfModule::EmitCtorBody(bool& skipBody)
  15471. {
  15472. auto methodInstance = mCurMethodInstance;
  15473. auto methodDef = methodInstance->mMethodDef;
  15474. auto methodDeclaration = methodDef->mMethodDeclaration;
  15475. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  15476. auto typeDef = mCurTypeInstance->mTypeDef;
  15477. BfCustomAttributes* customAttributes = NULL;
  15478. defer(delete customAttributes);
  15479. BfInvocationExpression* ctorInvocation = NULL;
  15480. BfAttributeState attributeState;
  15481. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  15482. if (ctorDeclaration != NULL)
  15483. {
  15484. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  15485. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  15486. {
  15487. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  15488. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  15489. }
  15490. }
  15491. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  15492. // Prologue
  15493. mBfIRBuilder->ClearDebugLocation();
  15494. bool hadThisInitializer = false;
  15495. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15496. {
  15497. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15498. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15499. if (targetToken->GetToken() == BfToken_This)
  15500. {
  15501. hadThisInitializer = true;
  15502. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  15503. mCurMethodState->LocalDefined(GetThisVariable());
  15504. }
  15505. }
  15506. // Zero out memory for default ctor
  15507. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()) && (methodInstance->mChainType != BfMethodChainType_ChainMember))
  15508. {
  15509. if (mCurTypeInstance->IsTypedPrimitive())
  15510. {
  15511. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15512. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  15513. }
  15514. else if (mCurTypeInstance->mInstSize > 0)
  15515. {
  15516. BfIRValue fillValue = GetConstValue8(0);
  15517. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  15518. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15519. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  15520. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  15521. }
  15522. }
  15523. BfAstNode* baseCtorNode = NULL;
  15524. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  15525. baseCtorNode = ctorInvocation->mTarget;
  15526. else if (methodDef->mBody != NULL)
  15527. baseCtorNode = methodDef->mBody;
  15528. else if (ctorDeclaration != NULL)
  15529. baseCtorNode = ctorDeclaration;
  15530. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15531. baseCtorNode = methodDef->mDeclaringType->GetRefNode();
  15532. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15533. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  15534. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  15535. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  15536. else
  15537. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  15538. bool calledCtorNoBody = false;
  15539. if ((mCurTypeInstance->IsTypedPrimitive()) && (!mCurTypeInstance->IsValuelessType()))
  15540. {
  15541. // Zero out typed primitives in ctor
  15542. mBfIRBuilder->CreateAlignedStore(GetDefaultValue(mCurTypeInstance->GetUnderlyingType()), mBfIRBuilder->GetArgument(0), mCurTypeInstance->mAlign);
  15543. }
  15544. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  15545. {
  15546. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  15547. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  15548. {
  15549. BfMethodDef* defaultCtor = NULL;
  15550. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  15551. {
  15552. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  15553. {
  15554. defaultCtor = methodDef;
  15555. }
  15556. }
  15557. if (defaultCtor != NULL)
  15558. {
  15559. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  15560. SetIllegalSrcPos();
  15561. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  15562. BfExprEvaluator exprEvaluator(this);
  15563. SizedArray<BfIRValue, 1> irArgs;
  15564. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  15565. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  15566. if (mIsComptimeModule)
  15567. mCompiler->mCeMachine->QueueMethod(moduleMethodInstance);
  15568. calledCtorNoBody = true;
  15569. }
  15570. }
  15571. }
  15572. // Initialize fields (if applicable)
  15573. if (mCurTypeInstance->IsBoxed())
  15574. {
  15575. skipBody = true;
  15576. }
  15577. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  15578. {
  15579. // Field initializers occur in CtorNoBody methods for extensions
  15580. }
  15581. else if (!hadThisInitializer)
  15582. {
  15583. // If we had a 'this' initializer, that other ctor will have initialized our fields
  15584. //auto
  15585. if ((!mCompiler->mIsResolveOnly) ||
  15586. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  15587. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  15588. {
  15589. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  15590. // to properly set the assigned flags
  15591. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  15592. bool hadInlineInitBlock = false;
  15593. BfScopeData scopeData;
  15594. scopeData.mInInitBlock = true;
  15595. auto _CheckInitBlock = [&](BfAstNode* node)
  15596. {
  15597. if (!hadInlineInitBlock)
  15598. {
  15599. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  15600. {
  15601. UpdateSrcPos(baseCtorNode);
  15602. if (methodDef->mBody == NULL)
  15603. SetIllegalSrcPos();
  15604. // NOP so we step onto the open paren of the method so we can choose to set into the field initializers or step over them
  15605. EmitEnsureInstructionAt();
  15606. BfType* thisType = mCurTypeInstance;
  15607. if (thisType->IsValueType())
  15608. thisType = CreateRefType(thisType);
  15609. SizedArray<BfIRMDNode, 1> diParamTypes;
  15610. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  15611. mCurMethodState->AddScope(&scopeData);
  15612. NewScopeState();
  15613. int flags = 0;
  15614. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  15615. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  15616. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  15617. String linkageName;
  15618. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mCurBuilder != NULL))
  15619. linkageName = StrFormat("%d", mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(mCurMethodInstance, "$initFields"));
  15620. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", linkageName, mCurFilePosition.mFileInstance->mDIFile,
  15621. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  15622. UpdateSrcPos(node);
  15623. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  15624. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  15625. //
  15626. {
  15627. auto loadedThis = GetThis();
  15628. // LLVM can't handle two variables pointing to the same value
  15629. BfIRValue copiedThisPtr;
  15630. copiedThisPtr = CreateAlloca(thisType);
  15631. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  15632. mBfIRBuilder->ClearDebugLocation(storeInst);
  15633. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  15634. }
  15635. hadInlineInitBlock = true;
  15636. }
  15637. else
  15638. {
  15639. // Just do a simple one
  15640. mCurMethodState->AddScope(&scopeData);
  15641. NewScopeState();
  15642. hadInlineInitBlock = true;
  15643. }
  15644. }
  15645. UpdateSrcPos(node);
  15646. };
  15647. for (auto fieldDef : typeDef->mFields)
  15648. {
  15649. // For extensions, only handle these fields in the appropriate extension
  15650. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15651. continue;
  15652. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  15653. {
  15654. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15655. if (!fieldInst->mFieldIncluded)
  15656. continue;
  15657. if (fieldInst->mDataIdx < 0)
  15658. continue;
  15659. auto initializer = fieldDef->GetInitializer();
  15660. if (fieldInst->IsAppendedObject())
  15661. {
  15662. UpdateSrcPos(fieldDef->GetNameNode());
  15663. AppendedObjectInit(fieldInst);
  15664. continue;
  15665. }
  15666. if (initializer == NULL)
  15667. {
  15668. continue;
  15669. // if (fieldDef->mProtection != BfProtection_Hidden)
  15670. // continue;
  15671. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  15672. // continue;
  15673. }
  15674. if (fieldInst->mResolvedType == NULL)
  15675. {
  15676. BF_ASSERT(mHadBuildError);
  15677. continue;
  15678. }
  15679. if (initializer != NULL)
  15680. {
  15681. _CheckInitBlock(initializer);
  15682. }
  15683. BfIRValue fieldAddr;
  15684. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  15685. {
  15686. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  15687. }
  15688. else
  15689. {
  15690. // Failed
  15691. }
  15692. auto assignValue = GetFieldInitializerValue(fieldInst);
  15693. if (mCurTypeInstance->IsUnion())
  15694. {
  15695. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  15696. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  15697. }
  15698. if ((fieldAddr) && (assignValue))
  15699. mBfIRBuilder->CreateAlignedStore(assignValue.mValue, fieldAddr, fieldInst->mResolvedType->mAlign);
  15700. }
  15701. }
  15702. EmitInitBlocks(_CheckInitBlock);
  15703. if (hadInlineInitBlock)
  15704. {
  15705. RestoreScopeState();
  15706. // This gets set to false because of AddScope but we actually are still in the head block
  15707. mCurMethodState->mInHeadScope = true;
  15708. // Make sure we emit a return even if we had a NoReturn call or return inside ourselves
  15709. mCurMethodState->mHadReturn = false;
  15710. mCurMethodState->mLeftBlockUncond = false;
  15711. }
  15712. }
  15713. else // Autocomplete case
  15714. {
  15715. BfScopeData scopeData;
  15716. scopeData.mInInitBlock = true;
  15717. mCurMethodState->AddScope(&scopeData);
  15718. NewScopeState();
  15719. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15720. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15721. // resolve pass, NOT the autocomplete expression
  15722. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15723. {
  15724. if (tempTypeDef->mFullName == typeDef->mFullName)
  15725. {
  15726. for (auto fieldDef : tempTypeDef->mFields)
  15727. {
  15728. auto initializer = fieldDef->GetInitializer();
  15729. if ((!fieldDef->mIsStatic) && (initializer != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  15730. {
  15731. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  15732. {
  15733. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  15734. sourceClassifier->VisitChild(initializer);
  15735. }
  15736. BfType* wantType = NULL;
  15737. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) &&
  15738. (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  15739. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowInferredSizedArray);
  15740. if ((wantType != NULL) &&
  15741. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  15742. wantType = NULL;
  15743. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  15744. if (fieldDef->mIsAppend)
  15745. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  15746. CreateValueFromExpression(initializer, wantType, exprFlags);
  15747. }
  15748. }
  15749. tempTypeDef->PopulateMemberSets();
  15750. BfMemberSetEntry* entry = NULL;
  15751. BfMethodDef* initMethodDef = NULL;
  15752. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  15753. if (entry != NULL)
  15754. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  15755. SizedArray<BfAstNode*, 8> initBodies;
  15756. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  15757. {
  15758. if (initMethodDef->mMethodType != BfMethodType_Init)
  15759. continue;
  15760. initBodies.Insert(0, initMethodDef->mBody);
  15761. }
  15762. for (auto body : initBodies)
  15763. VisitEmbeddedStatement(body);
  15764. }
  15765. }
  15766. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  15767. for (auto fieldDef : typeDef->mFields)
  15768. {
  15769. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->GetInitializer() != NULL))
  15770. {
  15771. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15772. if (fieldDef->GetInitializer() != NULL)
  15773. MarkFieldInitialized(fieldInst);
  15774. }
  15775. }
  15776. RestoreScopeState();
  15777. }
  15778. }
  15779. if (!methodInstance->mIsAutocompleteMethod)
  15780. {
  15781. if (auto autoDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  15782. {
  15783. BfExprEvaluator exprEvaluator(this);
  15784. for (int paramIdx = 0; paramIdx < methodDef->mParams.mSize; paramIdx++)
  15785. {
  15786. auto paramDef = methodDef->mParams[paramIdx];
  15787. auto& fieldInstance = mCurTypeInstance->mFieldInstances[paramIdx];
  15788. BF_ASSERT(paramDef->mName == fieldInstance.GetFieldDef()->mName);
  15789. if (fieldInstance.mDataIdx < 0)
  15790. continue;
  15791. if (paramDef->mParamKind != BfParamKind_Normal)
  15792. continue;
  15793. auto localVar = mCurMethodState->mLocals[paramIdx + 1];
  15794. BF_ASSERT(localVar->mName == paramDef->mName);
  15795. auto localVal = exprEvaluator.LoadLocal(localVar);
  15796. localVal = LoadOrAggregateValue(localVal);
  15797. if (!localVal.mType->IsVar())
  15798. {
  15799. auto thisVal = GetThis();
  15800. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance.mDataIdx);
  15801. if (mCurTypeInstance->IsUnion())
  15802. fieldPtr = mBfIRBuilder->CreateBitCast(fieldPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInstance.mResolvedType)));
  15803. mBfIRBuilder->CreateAlignedStore(localVal.mValue, fieldPtr, localVar->mResolvedType->mAlign);
  15804. }
  15805. MarkFieldInitialized(&fieldInstance);
  15806. }
  15807. }
  15808. }
  15809. // Call base ctor (if applicable)
  15810. BfTypeInstance* targetType = NULL;
  15811. BfAstNode* targetRefNode = NULL;
  15812. if (ctorDeclaration != NULL)
  15813. targetRefNode = ctorDeclaration->mInitializer;
  15814. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  15815. targetRefNode = invocationExpr->mTarget;
  15816. if (baseCtorNode != NULL)
  15817. {
  15818. UpdateSrcPos(baseCtorNode);
  15819. if (methodDef->mBody == NULL)
  15820. SetIllegalSrcPos();
  15821. }
  15822. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15823. {
  15824. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15825. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15826. }
  15827. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()) && (methodDef->mMethodType != BfMethodType_CtorNoBody))
  15828. {
  15829. auto baseType = mCurTypeInstance->mBaseType;
  15830. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  15831. ((baseType->mTypeDef != mCompiler->mValueTypeTypeDef) || (!mContext->mCanSkipValueTypeCtor)) &&
  15832. ((baseType->mTypeDef != mCompiler->mBfObjectTypeDef) || (!mContext->mCanSkipObjectCtor)))
  15833. {
  15834. // Try to find a ctor without any params first
  15835. BfMethodDef* matchedMethod = NULL;
  15836. bool hadCtorWithAllDefaults = false;
  15837. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  15838. for (int pass = 0; pass < 2; pass++)
  15839. {
  15840. baseType->mTypeDef->PopulateMemberSets();
  15841. BfMemberSetEntry* entry = NULL;
  15842. BfMethodDef* checkMethodDef = NULL;
  15843. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  15844. if (entry != NULL)
  15845. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  15846. while (checkMethodDef != NULL)
  15847. {
  15848. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  15849. if (isHiddenGenerated)
  15850. {
  15851. // Allow calling of the default base ctor if it is implicitly defined
  15852. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  15853. allowMethod = true;
  15854. }
  15855. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  15856. {
  15857. if (checkMethodDef->mParams.size() == 0)
  15858. {
  15859. if (matchedMethod != NULL)
  15860. {
  15861. // Has multiple matched methods - can happen from extensions
  15862. matchedMethod = NULL;
  15863. break;
  15864. }
  15865. matchedMethod = checkMethodDef;
  15866. }
  15867. else if (isHiddenGenerated)
  15868. {
  15869. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  15870. hadCtorWithAllDefaults = true;
  15871. }
  15872. }
  15873. checkMethodDef = checkMethodDef->mNextWithSameName;
  15874. }
  15875. if (matchedMethod != NULL)
  15876. break;
  15877. }
  15878. if ((HasExecutedOutput()) && (matchedMethod != NULL))
  15879. {
  15880. SizedArray<BfIRValue, 1> args;
  15881. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  15882. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  15883. {
  15884. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  15885. args.push_back(basePtr);
  15886. }
  15887. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  15888. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  15889. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  15890. if (callingConv != BfIRCallingConv_CDecl)
  15891. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  15892. if (mIsComptimeModule)
  15893. mCompiler->mCeMachine->QueueMethod(ctorBodyMethodInstance);
  15894. }
  15895. if (matchedMethod == NULL)
  15896. {
  15897. targetType = mCurTypeInstance->mBaseType;
  15898. if (ctorDeclaration != NULL)
  15899. targetRefNode = ctorDeclaration->mThisToken;
  15900. else if (typeDef->mTypeDeclaration != NULL)
  15901. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  15902. }
  15903. }
  15904. }
  15905. if (methodDef->mHasAppend)
  15906. {
  15907. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  15908. }
  15909. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  15910. {
  15911. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  15912. {
  15913. if (targetType == mCurTypeInstance)
  15914. {
  15915. auto thisVariable = GetThisVariable();
  15916. if (thisVariable != NULL)
  15917. {
  15918. thisVariable->mUnassignedFieldFlags = 0;
  15919. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15920. }
  15921. }
  15922. targetType = NULL;
  15923. }
  15924. }
  15925. auto autoComplete = mCompiler->GetAutoComplete();
  15926. if (targetType != NULL)
  15927. {
  15928. BfAstNode* refNode = methodDeclaration;
  15929. if (refNode == NULL)
  15930. refNode = typeDef->mTypeDeclaration;
  15931. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  15932. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  15933. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15934. {
  15935. auto invocationExpr = ctorInvocation;
  15936. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  15937. }
  15938. BfType* targetThisType = targetType;
  15939. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  15940. BfExprEvaluator exprEvaluator(this);
  15941. BfResolvedArgs argValues;
  15942. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15943. {
  15944. argValues.Init(&ctorInvocation->mArguments);
  15945. if (gDebugStuff)
  15946. {
  15947. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  15948. }
  15949. }
  15950. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15951. BfTypedValue appendIdxVal;
  15952. if (methodDef->mHasAppend)
  15953. {
  15954. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  15955. BF_ASSERT(localVar->mName == "appendIdx");
  15956. auto intRefType = localVar->mResolvedType;
  15957. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  15958. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  15959. }
  15960. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  15961. if (autoComplete != NULL)
  15962. {
  15963. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  15964. {
  15965. if (autoComplete->mMethodMatchInfo != NULL)
  15966. autoComplete->mIsCapturingMethodMatchInfo = true;
  15967. else
  15968. autoComplete->mIsCapturingMethodMatchInfo = false;
  15969. }
  15970. else
  15971. autoComplete->mIsCapturingMethodMatchInfo = false;
  15972. }
  15973. }
  15974. auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration);
  15975. if ((autoComplete != NULL) && (autoComplete->CheckFixit(methodDeclaration)) && (methodDeclaration != NULL) && (autoCtorDecl != NULL))
  15976. {
  15977. auto typeDecl = methodDef->mDeclaringType->mTypeDeclaration;
  15978. BfParserData* parser = typeDecl->GetSourceData()->ToParserData();
  15979. if (parser != NULL)
  15980. {
  15981. String fixitStr = "Expand auto constructor\t";
  15982. int insertPos = typeDecl->mSrcStart;
  15983. bool needsBlock = false;
  15984. if (auto defBlock = BfNodeDynCast<BfBlock>(typeDecl->mDefineNode))
  15985. {
  15986. insertPos = defBlock->mOpenBrace->mSrcStart + 1;
  15987. }
  15988. else if (auto tokenNode = BfNodeDynCast<BfTokenNode>(typeDecl->mDefineNode))
  15989. {
  15990. insertPos = tokenNode->mSrcStart;
  15991. fixitStr += StrFormat("delete|%s-%d|\x01",
  15992. autoComplete->FixitGetLocation(parser, tokenNode->mSrcStart).c_str(), tokenNode->mSrcEnd - tokenNode->mSrcStart);
  15993. needsBlock = true;
  15994. }
  15995. int srcStart = methodDeclaration->mSrcStart;
  15996. if ((autoCtorDecl->mPrefix == NULL) && (typeDecl->mColonToken != NULL))
  15997. srcStart = typeDecl->mColonToken->mSrcStart;
  15998. while ((srcStart > 0) && (::isspace((uint8)parser->mSrc[srcStart - 1])))
  15999. srcStart--;
  16000. fixitStr += StrFormat("expand|%s|%d|",
  16001. parser->mFileName.c_str(), insertPos);
  16002. if (needsBlock)
  16003. fixitStr += "\t";
  16004. else
  16005. fixitStr += "\f";
  16006. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16007. {
  16008. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16009. paramStr.Replace('\n', '\r');
  16010. fixitStr += "public ";
  16011. fixitStr += paramStr;
  16012. fixitStr += ";\r";
  16013. }
  16014. fixitStr += "\rpublic this(";
  16015. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16016. {
  16017. if (paramIdx > 0)
  16018. fixitStr += ", ";
  16019. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16020. paramStr.Replace('\n', '\r');
  16021. fixitStr += paramStr;
  16022. }
  16023. fixitStr += ")\t";
  16024. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16025. {
  16026. if (paramIdx > 0)
  16027. fixitStr += "\r";
  16028. auto nameNode = autoCtorDecl->mParams[paramIdx]->mNameNode;
  16029. if (nameNode == NULL)
  16030. continue;
  16031. String nameStr = nameNode->ToString();
  16032. fixitStr += "this.";
  16033. fixitStr += nameStr;
  16034. fixitStr += " = ";
  16035. fixitStr += nameStr;
  16036. fixitStr += ";";
  16037. }
  16038. fixitStr += "\b";
  16039. if (needsBlock)
  16040. fixitStr += "\b";
  16041. fixitStr += StrFormat("\x01""delete|%s-%d|",
  16042. autoComplete->FixitGetLocation(parser, srcStart).c_str(), autoCtorDecl->mSrcEnd - srcStart);
  16043. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", fixitStr.c_str()));
  16044. }
  16045. }
  16046. }
  16047. void BfModule::EmitEnumToStringBody()
  16048. {
  16049. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16050. auto strVal = CreateAlloca(stringType);
  16051. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  16052. BfExprEvaluator exprEvaluator(this);
  16053. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16054. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  16055. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  16056. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  16057. BfType* discriminatorType = NULL;
  16058. BfTypedValue rawPayload;
  16059. BfIRValue enumVal;
  16060. if (mCurTypeInstance->IsPayloadEnum())
  16061. {
  16062. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  16063. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  16064. enumTypedValue = LoadValue(enumTypedValue);
  16065. enumVal = enumTypedValue.mValue;
  16066. rawPayload = ExtractValue(GetThis(), NULL, 1);
  16067. }
  16068. else
  16069. enumVal = mBfIRBuilder->GetArgument(0);
  16070. Array<BfType*> paramTypes;
  16071. paramTypes.Add(stringType);
  16072. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16073. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  16074. HashSet<int64> handledCases;
  16075. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16076. {
  16077. if (fieldInstance.mIsEnumPayloadCase)
  16078. {
  16079. int tagId = -fieldInstance.mDataIdx - 1;
  16080. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16081. mBfIRBuilder->AddBlock(caseBlock);
  16082. mBfIRBuilder->SetInsertPoint(caseBlock);
  16083. BF_ASSERT(discriminatorType->IsPrimitiveType());
  16084. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  16085. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16086. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16087. auto stringDestVal = LoadValue(stringDestAddr);
  16088. SizedArray<BfIRValue, 2> args;
  16089. args.Add(stringDestVal.mValue);
  16090. args.Add(caseStr);
  16091. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16092. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  16093. BF_ASSERT(payloadType->IsTuple());
  16094. if (payloadType->mFieldInstances.size() != 0)
  16095. {
  16096. auto payload = rawPayload;
  16097. if (payload.mType != payloadType)
  16098. {
  16099. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  16100. }
  16101. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  16102. SizedArray<BfIRValue, 2> irArgs;
  16103. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  16104. stringDestVal = LoadValue(stringDestAddr);
  16105. irArgs.Add(stringDestVal.mValue);
  16106. exprEvaluator.CreateCall(NULL, toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  16107. }
  16108. mBfIRBuilder->CreateBr(endBlock);
  16109. continue;
  16110. }
  16111. if (fieldInstance.mConstIdx == -1)
  16112. continue;
  16113. // Only allow compact 'ValA, ValB' enum declaration fields through
  16114. auto fieldDef = fieldInstance.GetFieldDef();
  16115. auto fieldDecl = fieldDef->mFieldDeclaration;
  16116. if ((fieldDecl == NULL) || (fieldDef->mTypeRef != NULL))
  16117. continue;
  16118. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  16119. if (!handledCases.TryAdd(constant->mInt64, NULL))
  16120. {
  16121. // Duplicate
  16122. continue;
  16123. }
  16124. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16125. mBfIRBuilder->AddBlock(caseBlock);
  16126. mBfIRBuilder->SetInsertPoint(caseBlock);
  16127. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  16128. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16129. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16130. mBfIRBuilder->CreateStore(caseStr, strVal);
  16131. mBfIRBuilder->CreateBr(appendBlock);
  16132. }
  16133. mBfIRBuilder->AddBlock(appendBlock);
  16134. mBfIRBuilder->SetInsertPoint(appendBlock);
  16135. SizedArray<BfIRValue, 2> args;
  16136. auto stringDestVal = LoadValue(stringDestAddr);
  16137. args.Add(stringDestVal.mValue);
  16138. args.Add(mBfIRBuilder->CreateLoad(strVal));
  16139. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16140. mBfIRBuilder->CreateBr(endBlock);
  16141. mBfIRBuilder->AddBlock(noMatchBlock);
  16142. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  16143. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  16144. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  16145. args.clear();
  16146. args.Add(int64Val);
  16147. stringDestVal = LoadValue(stringDestAddr);
  16148. args.Add(stringDestVal.mValue);
  16149. exprEvaluator.CreateCall(NULL, toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  16150. mBfIRBuilder->CreateBr(endBlock);
  16151. mBfIRBuilder->AddBlock(endBlock);
  16152. mBfIRBuilder->SetInsertPoint(endBlock);
  16153. }
  16154. void BfModule::EmitTupleToStringBody()
  16155. {
  16156. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16157. BfExprEvaluator exprEvaluator(this);
  16158. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16159. Array<BfType*> paramTypes;
  16160. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  16161. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16162. paramTypes.Clear();
  16163. paramTypes.Add(stringType);
  16164. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16165. auto _AppendChar = [&](char c)
  16166. {
  16167. SizedArray<BfIRValue, 2> args;
  16168. auto stringDestVal = LoadValue(stringDestRef);
  16169. args.Add(stringDestVal.mValue);
  16170. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  16171. exprEvaluator.CreateCall(NULL, appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  16172. };
  16173. int fieldIdx = 0;
  16174. auto thisValue = GetThis();
  16175. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  16176. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  16177. BfIRValue commaStr;
  16178. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  16179. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  16180. _AppendChar('(');
  16181. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16182. {
  16183. if (fieldInstance.mDataIdx == -1)
  16184. continue;
  16185. if (fieldIdx > 0)
  16186. {
  16187. if (!commaStr)
  16188. commaStr = GetStringObjectValue(", ");
  16189. SizedArray<BfIRValue, 2> args;
  16190. auto stringDestVal = LoadValue(stringDestRef);
  16191. args.Add(stringDestVal.mValue);
  16192. args.Add(commaStr);
  16193. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16194. }
  16195. fieldIdx++;
  16196. if (fieldInstance.mResolvedType->IsValuelessType())
  16197. continue;
  16198. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  16199. if (fieldValue.mType->IsPrimitiveType())
  16200. {
  16201. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  16202. }
  16203. auto typeInstance = fieldValue.mType->ToTypeInstance();
  16204. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  16205. {
  16206. BfExprEvaluator exprEvaluator(this);
  16207. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16208. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16209. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  16210. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  16211. methodMatcher.TryDevirtualizeCall(fieldValue);
  16212. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16213. BfResolvedArg resolvedArg;
  16214. auto stringDestVal = LoadValue(stringDestRef);
  16215. resolvedArg.mTypedValue = stringDestVal;
  16216. resolvedArg.mResolvedType = stringDestVal.mType;
  16217. resolvedArgs.Add(resolvedArg);
  16218. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16219. continue;
  16220. }
  16221. if (fieldValue.mType->IsObjectOrInterface())
  16222. {
  16223. fieldValue = LoadValue(fieldValue);
  16224. BF_ASSERT(!fieldValue.IsAddr());
  16225. SizedArray<BfIRValue, 2> args;
  16226. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16227. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16228. stringDestVal = LoadValue(stringDestVal);
  16229. args.Add(stringDestVal.mValue);
  16230. exprEvaluator.CreateCall(NULL, toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  16231. continue;
  16232. }
  16233. BfExprEvaluator exprEvaluator(this);
  16234. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16235. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16236. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  16237. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  16238. methodMatcher.TryDevirtualizeCall(fieldValue);
  16239. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  16240. {
  16241. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  16242. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  16243. // Just append the type name
  16244. String typeName = TypeToString(fieldInstance.mResolvedType);
  16245. auto strVal = GetStringObjectValue(typeName);
  16246. SizedArray<BfIRValue, 2> args;
  16247. auto stringDestVal = LoadValue(stringDestRef);
  16248. args.Add(stringDestVal.mValue);
  16249. args.Add(strVal);
  16250. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16251. continue;
  16252. }
  16253. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16254. BfResolvedArg resolvedArg;
  16255. auto stringDestVal = LoadValue(stringDestRef);
  16256. resolvedArg.mTypedValue = stringDestVal;
  16257. resolvedArg.mResolvedType = stringDestVal.mType;
  16258. resolvedArgs.Add(resolvedArg);
  16259. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16260. }
  16261. _AppendChar(')');
  16262. }
  16263. void BfModule::EmitIteratorBlock(bool& skipBody)
  16264. {
  16265. auto methodInstance = mCurMethodInstance;
  16266. auto methodDef = methodInstance->mMethodDef;
  16267. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16268. auto typeDef = mCurTypeInstance->mTypeDef;
  16269. BfType* innerRetType = NULL;
  16270. BfTypeInstance* usingInterface = NULL;
  16271. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  16272. if (retTypeInst != NULL)
  16273. {
  16274. if ((retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef)) ||
  16275. (retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumeratorTypeDef)))
  16276. {
  16277. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  16278. }
  16279. }
  16280. if (innerRetType == NULL)
  16281. {
  16282. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  16283. return;
  16284. }
  16285. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  16286. if (blockBody == NULL)
  16287. return;
  16288. }
  16289. void BfModule::EmitGCMarkAppended(BfTypedValue markVal)
  16290. {
  16291. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  16292. if (gcType == NULL)
  16293. return;
  16294. BfModuleMethodInstance markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "MarkAppendedObject", 1);
  16295. if (!markFromGCThreadMethodInstance)
  16296. return;
  16297. SizedArray<BfIRValue, 1> args;
  16298. args.push_back(mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16299. BfExprEvaluator exprEvaluator(this);
  16300. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16301. }
  16302. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  16303. {
  16304. auto fieldType = markVal.mType;
  16305. auto fieldTypeInst = fieldType->ToTypeInstance();
  16306. if (fieldType == NULL)
  16307. return;
  16308. if (!markVal.mType->IsComposite())
  16309. markVal = LoadValue(markVal);
  16310. BfExprEvaluator exprEvaluator(this);
  16311. PopulateType(markVal.mType, BfPopulateType_Data);
  16312. if (markVal.mType->IsObjectOrInterface())
  16313. {
  16314. BfIRValue val = markVal.mValue;
  16315. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  16316. SizedArray<BfIRValue, 1> args;
  16317. args.push_back(val);
  16318. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16319. }
  16320. else if (fieldType->IsSizedArray())
  16321. {
  16322. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)fieldType;
  16323. if (sizedArrayType->mElementType->WantsGCMarking())
  16324. {
  16325. BfTypedValue arrayValue = markVal;
  16326. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  16327. auto itr = CreateAlloca(intPtrType);
  16328. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  16329. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  16330. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  16331. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  16332. mBfIRBuilder->CreateBr(loopBB);
  16333. mBfIRBuilder->SetInsertPoint(loopBB);
  16334. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  16335. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  16336. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  16337. mBfIRBuilder->SetInsertPoint(bodyBB);
  16338. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16339. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16340. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  16341. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16342. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16343. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  16344. mBfIRBuilder->CreateStore(incValue, itr);
  16345. mBfIRBuilder->CreateBr(loopBB);
  16346. mBfIRBuilder->SetInsertPoint(doneBB);
  16347. }
  16348. }
  16349. else if ((fieldType->IsComposite()) && (!fieldType->IsTypedPrimitive()) && (fieldTypeInst != NULL))
  16350. {
  16351. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  16352. if (markMemberMethodInstance)
  16353. {
  16354. SizedArray<BfIRValue, 1> args;
  16355. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  16356. if (markVal.mType != methodOwner)
  16357. markVal = Cast(NULL, markVal, methodOwner);
  16358. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  16359. exprEvaluator.CreateCall(NULL, markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  16360. }
  16361. }
  16362. }
  16363. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  16364. {
  16365. Array<BfMethodInstance*> methodInstances;
  16366. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  16367. {
  16368. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  16369. auto chainedMethodInst = methodInstGroup.mDefault;
  16370. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  16371. {
  16372. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  16373. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  16374. {
  16375. methodInstances.push_back(chainedMethodInst);
  16376. }
  16377. }
  16378. }
  16379. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  16380. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  16381. {
  16382. bool isBetter;
  16383. bool isWorse;
  16384. CompareDeclTypes(mCurTypeInstance, lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  16385. if (isBetter == isWorse)
  16386. {
  16387. return false;
  16388. }
  16389. return isWorse;
  16390. });
  16391. if (reverse)
  16392. std::reverse(methodInstances.begin(), methodInstances.end());
  16393. for (auto chainedMethodInst : methodInstances)
  16394. {
  16395. auto declModule = this;
  16396. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  16397. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  16398. BfExprEvaluator exprEvaluator(this);
  16399. SizedArray<BfIRValue, 1> args;
  16400. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  16401. exprEvaluator.CreateCall(NULL, moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  16402. }
  16403. }
  16404. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  16405. {
  16406. BF_ASSERT(mCurMethodInstance->mIsReified);
  16407. if (mCurTypeInstance->mHotTypeData == NULL)
  16408. {
  16409. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  16410. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  16411. }
  16412. auto hotMethod = mCurMethodInstance->mHotMethod;
  16413. for (auto depData : hotMethod->mReferences)
  16414. {
  16415. // Only virtual decls are allowed to already be there
  16416. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  16417. }
  16418. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  16419. int prevSize = (int)hotMethod->mReferences.size();
  16420. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  16421. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  16422. refCount++;
  16423. hotMethod->mReferences.Reserve(refCount);
  16424. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  16425. {
  16426. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  16427. hotThis->mRefCount++;
  16428. hotMethod->mReferences.Insert(0, hotThis);
  16429. prevSize++;
  16430. }
  16431. for (auto val : builder->mAllocatedData)
  16432. {
  16433. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  16434. hotMethod->mReferences.Add(hotAllocation);
  16435. }
  16436. for (auto val : builder->mUsedData)
  16437. hotMethod->mReferences.Add(val);
  16438. for (auto val : builder->mCalledMethods)
  16439. hotMethod->mReferences.Add(val);
  16440. for (auto val : builder->mDevirtualizedCalledMethods)
  16441. {
  16442. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  16443. hotMethod->mReferences.Add(devirtualizedMethod);
  16444. }
  16445. for (auto val : builder->mFunctionPtrs)
  16446. {
  16447. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  16448. hotMethod->mReferences.Add(funcRef);
  16449. }
  16450. for (auto val : builder->mInnerMethods)
  16451. {
  16452. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  16453. hotMethod->mReferences.Add(innerMethod);
  16454. }
  16455. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  16456. {
  16457. auto depData = hotMethod->mReferences[refIdx];
  16458. BF_ASSERT(depData != NULL);
  16459. depData->mRefCount++;
  16460. }
  16461. }
  16462. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  16463. {
  16464. auto methodDef = methodInstance->mMethodDef;
  16465. auto methodDeclaration = methodDef->mMethodDeclaration;
  16466. bool isThisStruct = false;
  16467. if (thisType != NULL)
  16468. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  16469. int argIdx = 0;
  16470. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16471. argIdx++;
  16472. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16473. if (!methodDef->mIsStatic)
  16474. {
  16475. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16476. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16477. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  16478. paramVar->mIsBumpAlloc = true;
  16479. paramVar->mResolvedType = thisType;
  16480. paramVar->mName.Reference("this");
  16481. if (!thisType->IsValuelessType())
  16482. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16483. else
  16484. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  16485. if ((!mIsComptimeModule) && (thisType->IsSplattable()) && (methodInstance->AllowsSplatting(-1)))
  16486. {
  16487. if (!thisType->IsTypedPrimitive())
  16488. paramVar->mIsSplat = true;
  16489. }
  16490. else if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  16491. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  16492. auto thisTypeInst = thisType->ToTypeInstance();
  16493. paramVar->mIsStruct = isThisStruct;
  16494. paramVar->mAddr = BfIRValue();
  16495. paramVar->mIsThis = true;
  16496. paramVar->mParamIdx = -1;
  16497. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  16498. {
  16499. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  16500. }
  16501. else
  16502. {
  16503. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16504. }
  16505. paramVar->mReadFromId = -1;
  16506. paramVar->Init();
  16507. if (methodDeclaration == NULL)
  16508. UseDefaultSrcPos();
  16509. AddLocalVariableDef(paramVar);
  16510. if (!thisType->IsValuelessType())
  16511. {
  16512. if (wantsDIData)
  16513. {
  16514. BfType* thisPtrType = thisType;
  16515. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  16516. if (!thisType->IsValueType())
  16517. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  16518. else if (!paramVar->mIsSplat)
  16519. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  16520. diParams->push_back(diType);
  16521. }
  16522. if (paramVar->mIsSplat)
  16523. {
  16524. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16525. }
  16526. else
  16527. {
  16528. argIdx++;
  16529. if (loweredTypeCode2 != BfTypeCode_None)
  16530. argIdx++;
  16531. }
  16532. }
  16533. }
  16534. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16535. argIdx++;
  16536. bool hadParams = false;
  16537. bool hasDefault = false;
  16538. int compositeVariableIdx = -1;
  16539. int paramIdx = 0;
  16540. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16541. {
  16542. // We already issues a type error for this param if we had one in declaration processing
  16543. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  16544. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  16545. paramVar->mIsBumpAlloc = true;
  16546. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16547. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16548. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  16549. auto resolvedType = methodInstance->GetParamType(paramIdx);
  16550. if (resolvedType == NULL)
  16551. {
  16552. AssertErrorState();
  16553. paramVar->mParamFailed = true;
  16554. }
  16555. prevIgnoreErrors.Restore();
  16556. PopulateType(resolvedType, BfPopulateType_Declaration);
  16557. paramVar->mResolvedType = resolvedType;
  16558. int namePrefixCount = 0;
  16559. methodInstance->GetParamName(paramIdx, paramVar->mName, namePrefixCount);
  16560. paramVar->mNamePrefixCount = (uint8)namePrefixCount;
  16561. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  16562. if (!isParamSkipped)
  16563. {
  16564. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16565. if (resolvedType->IsMethodRef())
  16566. {
  16567. paramVar->mIsSplat = true;
  16568. }
  16569. else if ((!mIsComptimeModule) && (resolvedType->IsComposite()) && (resolvedType->IsSplattable()))
  16570. {
  16571. if (methodInstance->AllowsSplatting(paramIdx))
  16572. {
  16573. auto resolveTypeInst = resolvedType->ToTypeInstance();
  16574. if ((resolveTypeInst != NULL) && (resolveTypeInst->mIsCRepr))
  16575. paramVar->mIsSplat = true;
  16576. else
  16577. {
  16578. int splatCount = resolvedType->GetSplatCount();
  16579. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16580. paramVar->mIsSplat = true;
  16581. }
  16582. }
  16583. }
  16584. }
  16585. else
  16586. {
  16587. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  16588. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  16589. }
  16590. paramVar->mIsLowered = (!mIsComptimeModule) && resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  16591. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  16592. paramVar->mParamIdx = paramIdx;
  16593. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  16594. paramVar->mReadFromId = 0;
  16595. if (resolvedType->IsRef())
  16596. {
  16597. auto refType = (BfRefType*)resolvedType;
  16598. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  16599. if (refType->mRefKind == BfRefType::RefKind_In)
  16600. {
  16601. paramVar->mIsReadOnly = true;
  16602. }
  16603. }
  16604. else
  16605. {
  16606. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16607. if (methodDef->mMethodType != BfMethodType_Mixin)
  16608. paramVar->mIsReadOnly = true;
  16609. }
  16610. if (paramVar->mResolvedType->IsGenericParam())
  16611. {
  16612. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  16613. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  16614. {
  16615. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  16616. paramVar->mResolvedType = typedVal.mType;
  16617. paramVar->mConstValue = typedVal.mValue;
  16618. }
  16619. }
  16620. if (paramVar->mResolvedType->IsConstExprValue())
  16621. {
  16622. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  16623. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  16624. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  16625. BF_ASSERT(unspecParamType->IsGenericParam());
  16626. if (unspecParamType->IsGenericParam())
  16627. {
  16628. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  16629. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  16630. {
  16631. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  16632. if (genericParamInst->mTypeConstraint != NULL)
  16633. {
  16634. BfExprEvaluator exprEvaluator(this);
  16635. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  16636. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  16637. auto checkType = genericParamInst->mTypeConstraint;
  16638. if (checkType->IsTypedPrimitive())
  16639. checkType = checkType->GetUnderlyingType();
  16640. auto typedVal = exprEvaluator.mResult;
  16641. if ((typedVal) && (typedVal.mType != checkType))
  16642. typedVal = Cast(NULL, typedVal, checkType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  16643. if ((typedVal.mType == checkType) && (typedVal.mValue.IsConst()))
  16644. {
  16645. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  16646. paramVar->mConstValue = typedVal.mValue;
  16647. BF_ASSERT(paramVar->mConstValue.IsConst());
  16648. paramVar->mIsConst = true;
  16649. }
  16650. else
  16651. {
  16652. AssertErrorState();
  16653. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  16654. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  16655. paramVar->mIsConst = true;
  16656. }
  16657. if (paramVar->mResolvedType->IsObject())
  16658. {
  16659. BfTypedValue typedVal(paramVar->mConstValue, paramVar->mResolvedType);
  16660. FixValueActualization(typedVal);
  16661. if (typedVal.mValue.IsConst())
  16662. paramVar->mConstValue = typedVal.mValue;
  16663. }
  16664. }
  16665. }
  16666. }
  16667. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  16668. if (paramVar->mResolvedType->IsConstExprValue())
  16669. {
  16670. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  16671. //AssertErrorState();
  16672. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  16673. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  16674. paramVar->mIsConst = true;
  16675. }
  16676. }
  16677. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  16678. {
  16679. if (compositeVariableIdx == -1)
  16680. {
  16681. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  16682. BfLocalVariable* localVar = new BfLocalVariable();
  16683. auto paramInst = &methodInstance->mParams[paramIdx];
  16684. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  16685. localVar->mName = paramDef->mName;
  16686. localVar->mNamePrefixCount = paramDef->mNamePrefixCount;
  16687. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  16688. localVar->mCompositeCount = 0;
  16689. DoAddLocalVariable(localVar);
  16690. }
  16691. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  16692. paramVar->mIsImplicitParam = true;
  16693. }
  16694. if (!mCurTypeInstance->IsDelegateOrFunction())
  16695. CheckVariableDef(paramVar);
  16696. paramVar->Init();
  16697. AddLocalVariableDef(paramVar);
  16698. if (!isParamSkipped)
  16699. {
  16700. if (wantsDIData)
  16701. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  16702. if (paramVar->mIsSplat)
  16703. {
  16704. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16705. }
  16706. else
  16707. {
  16708. argIdx++;
  16709. }
  16710. if (loweredTypeCode2 != BfTypeCode_None)
  16711. argIdx++;
  16712. }
  16713. }
  16714. // Try to find an ending delegate params composite
  16715. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  16716. {
  16717. auto paramDef = methodDef->mParams.back();
  16718. if (paramDef->mParamKind == BfParamKind_Params)
  16719. {
  16720. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  16721. if (paramsType == NULL)
  16722. {
  16723. // Had error or 'var'
  16724. }
  16725. else if (paramsType->IsGenericParam())
  16726. {
  16727. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  16728. if (genericParamInstance->mTypeConstraint != NULL)
  16729. {
  16730. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16731. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16732. ((typeInstConstraint != NULL) &&
  16733. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  16734. {
  16735. BfLocalVariable* localVar = new BfLocalVariable();
  16736. localVar->mName = paramDef->mName;
  16737. localVar->mResolvedType = paramsType;
  16738. localVar->mCompositeCount = 0;
  16739. DoAddLocalVariable(localVar);
  16740. }
  16741. }
  16742. }
  16743. else if (paramsType->IsDelegate())
  16744. {
  16745. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  16746. if (invokeMethodInstance != NULL)
  16747. {
  16748. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  16749. // and wasn't cleared by the preceding loop
  16750. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  16751. BfLocalVariable* localVar = new BfLocalVariable();
  16752. localVar->mName = paramDef->mName;
  16753. localVar->mResolvedType = paramsType;
  16754. localVar->mCompositeCount = 0;
  16755. DoAddLocalVariable(localVar);
  16756. }
  16757. }
  16758. }
  16759. }
  16760. }
  16761. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  16762. {
  16763. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  16764. // return;
  16765. auto startMethodState = mCurMethodState;
  16766. auto _ClearState = [&]()
  16767. {
  16768. mCurMethodState->mLocalMethods.Clear();
  16769. for (auto& local : mCurMethodState->mLocals)
  16770. {
  16771. if (local->mIsBumpAlloc)
  16772. local->~BfLocalVariable();
  16773. else
  16774. delete local;
  16775. }
  16776. mCurMethodState->mLocals.Clear();
  16777. mCurMethodState->mLocalVarSet.Clear();
  16778. };
  16779. while (true)
  16780. {
  16781. bool didWork = false;
  16782. // Don't process local methods if we had a build error - this isn't just an optimization, it keeps us from showing the same error twice since
  16783. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  16784. // however (compiler bug), so this is the safest way
  16785. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  16786. {
  16787. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  16788. {
  16789. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  16790. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  16791. if (!mHadBuildError)
  16792. {
  16793. // Process as a closure - that allows us to look back and see the const locals and stuff
  16794. BfClosureState closureState;
  16795. mCurMethodState->mClosureState = &closureState;
  16796. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  16797. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  16798. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  16799. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  16800. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  16801. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  16802. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  16803. _ClearState();
  16804. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  16805. {
  16806. auto localVar = new BfLocalVariable();
  16807. *localVar = constLocal;
  16808. DoAddLocalVariable(localVar);
  16809. }
  16810. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  16811. bool doProcess = !mCompiler->mCanceling;
  16812. if (doProcess)
  16813. {
  16814. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  16815. ProcessMethod(deferredLocalMethod->mMethodInstance);
  16816. }
  16817. }
  16818. delete deferredLocalMethod;
  16819. mContext->CheckLockYield();
  16820. didWork = true;
  16821. }
  16822. mCurMethodState->mDeferredLocalMethods.Clear();
  16823. }
  16824. for (auto& kv : mCurMethodState->mLocalMethodCache)
  16825. {
  16826. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  16827. }
  16828. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  16829. {
  16830. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  16831. {
  16832. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  16833. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  16834. BfClosureState closureState;
  16835. mCurMethodState->mClosureState = &closureState;
  16836. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  16837. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  16838. if (lambdaInstance->mClosureTypeInstance != NULL)
  16839. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  16840. else
  16841. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  16842. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  16843. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  16844. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  16845. _ClearState();
  16846. for (auto& constLocal : lambdaInstance->mConstLocals)
  16847. {
  16848. //if (constLocal.mIsThis)
  16849. {
  16850. // Valueless 'this'
  16851. closureState.mConstLocals.Add(constLocal);
  16852. }
  16853. /*else
  16854. {
  16855. auto localVar = new BfLocalVariable();
  16856. *localVar = constLocal;
  16857. DoAddLocalVariable(localVar);
  16858. }*/
  16859. }
  16860. BfMethodInstanceGroup methodInstanceGroup;
  16861. methodInstanceGroup.mOwner = mCurTypeInstance;
  16862. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  16863. bool doProcess = !mCompiler->mCanceling;
  16864. if (doProcess)
  16865. {
  16866. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  16867. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  16868. ProcessMethod(lambdaInstance->mMethodInstance);
  16869. lambdaInstance->mMethodInstance->mMethodInstanceGroup = NULL;
  16870. if (lambdaInstance->mDtorMethodInstance != NULL)
  16871. {
  16872. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  16873. auto startMethodState2 = mCurMethodState;
  16874. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  16875. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = NULL;
  16876. }
  16877. }
  16878. didWork = true;
  16879. }
  16880. mContext->CheckLockYield();
  16881. mCurMethodState->mDeferredLambdaInstances.Clear();
  16882. }
  16883. if (!didWork)
  16884. break;
  16885. }
  16886. }
  16887. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance, bool isAppendObject)
  16888. {
  16889. if (checkType->IsComposite())
  16890. PopulateType(checkType, BfPopulateType_Data);
  16891. if (!checkType->WantsGCMarking())
  16892. return;
  16893. auto typeInstance = checkType->ToTypeInstance();
  16894. bool callMarkMethod = false;
  16895. // Call the actual marking method
  16896. if (memberDepth == 0)
  16897. {
  16898. // Don't call marking method on self
  16899. }
  16900. else if (checkType->IsObjectOrInterface())
  16901. {
  16902. if (!objectOffsets.Add(curOffset))
  16903. {
  16904. return;
  16905. }
  16906. callMarkMethod = true;
  16907. }
  16908. else if (checkType->IsSizedArray())
  16909. {
  16910. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  16911. if (sizedArrayType->mElementType->WantsGCMarking())
  16912. {
  16913. BfTypedValue arrayValue = thisValue;
  16914. if (thisValue.mType != checkType)
  16915. {
  16916. BfIRValue srcValue = thisValue.mValue;
  16917. if (curOffset != 0)
  16918. {
  16919. if (!thisValue.mType->IsPointer())
  16920. {
  16921. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  16922. auto int8PtrType = CreatePointerType(int8Type);
  16923. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  16924. }
  16925. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  16926. }
  16927. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  16928. }
  16929. if (sizedArrayType->mElementCount > 6)
  16930. {
  16931. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  16932. auto itr = CreateAlloca(intPtrType);
  16933. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  16934. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  16935. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  16936. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  16937. mBfIRBuilder->CreateBr(loopBB);
  16938. mBfIRBuilder->SetInsertPoint(loopBB);
  16939. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  16940. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  16941. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  16942. mBfIRBuilder->SetInsertPoint(bodyBB);
  16943. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16944. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16945. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  16946. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16947. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16948. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  16949. mBfIRBuilder->CreateStore(incValue, itr);
  16950. mBfIRBuilder->CreateBr(loopBB);
  16951. mBfIRBuilder->SetInsertPoint(doneBB);
  16952. }
  16953. else
  16954. {
  16955. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  16956. {
  16957. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16958. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16959. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  16960. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16961. HashSet<int> objectOffsets;
  16962. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16963. }
  16964. }
  16965. }
  16966. }
  16967. else if (typeInstance != NULL)
  16968. {
  16969. typeInstance->mTypeDef->PopulateMemberSets();
  16970. BfMemberSetEntry* entry = NULL;
  16971. BfMethodDef* methodDef = NULL;
  16972. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  16973. {
  16974. methodDef = (BfMethodDef*)entry->mMemberDef;
  16975. if (methodDef->HasBody())
  16976. {
  16977. callMarkMethod = true;
  16978. }
  16979. }
  16980. }
  16981. if (callMarkMethod)
  16982. {
  16983. BfTypedValue markValue;
  16984. auto memberType = checkType;
  16985. if (memberType->IsObjectOrInterface())
  16986. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  16987. auto memberPtrType = CreatePointerType(memberType);
  16988. if (curOffset == 0)
  16989. {
  16990. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  16991. }
  16992. else
  16993. {
  16994. if (!thisValue.mType->IsPointer())
  16995. {
  16996. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  16997. auto int8PtrType = CreatePointerType(int8Type);
  16998. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  16999. }
  17000. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  17001. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17002. }
  17003. if (isAppendObject)
  17004. EmitGCMarkAppended(markValue);
  17005. else
  17006. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17007. return;
  17008. }
  17009. auto methodDef = mCurMethodInstance->mMethodDef;
  17010. if (checkType->IsPayloadEnum())
  17011. {
  17012. for (auto& fieldInst : typeInstance->mFieldInstances)
  17013. {
  17014. if (!fieldInst.mIsEnumPayloadCase)
  17015. continue;
  17016. auto fieldDef = fieldInst.GetFieldDef();
  17017. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17018. }
  17019. return;
  17020. }
  17021. if (typeInstance == NULL)
  17022. return;
  17023. for (auto& fieldInst : typeInstance->mFieldInstances)
  17024. {
  17025. auto fieldDef = fieldInst.GetFieldDef();
  17026. if (fieldDef == NULL)
  17027. continue;
  17028. if (fieldDef->mIsStatic)
  17029. continue;
  17030. if (typeInstance == mCurTypeInstance)
  17031. {
  17032. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  17033. // we may be marking member values that can never contain a value anyway, but this is benign
  17034. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17035. continue;
  17036. }
  17037. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance, fieldInst.IsAppendedObject());
  17038. }
  17039. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  17040. {
  17041. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17042. }
  17043. }
  17044. void BfModule::EmitGCMarkMembers()
  17045. {
  17046. auto methodDef = mCurMethodInstance->mMethodDef;
  17047. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  17048. BfModuleMethodInstance markFromGCThreadMethodInstance;
  17049. if (gcType != NULL)
  17050. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  17051. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  17052. {
  17053. if (mCurTypeInstance->IsBoxed())
  17054. {
  17055. // This already gets filled in by the normal boxed forwarding
  17056. }
  17057. else
  17058. {
  17059. auto thisValue = GetThis();
  17060. if (thisValue.IsSplat())
  17061. {
  17062. BfIRFunction func = mCurMethodInstance->mIRFunction;
  17063. int argIdx = 0;
  17064. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  17065. {
  17066. if (checkType->IsStruct())
  17067. {
  17068. auto checkTypeInstance = checkType->ToTypeInstance();
  17069. if (checkTypeInstance->mBaseType != NULL)
  17070. checkTypeLambda(checkTypeInstance->mBaseType);
  17071. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  17072. {
  17073. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  17074. if (fieldInstance->mDataIdx >= 0)
  17075. checkTypeLambda(fieldInstance->GetResolvedType());
  17076. }
  17077. }
  17078. else if (checkType->IsMethodRef())
  17079. {
  17080. BFMODULE_FATAL(this, "Not handled");
  17081. }
  17082. else if (checkType->WantsGCMarking())
  17083. {
  17084. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  17085. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17086. argIdx++;
  17087. }
  17088. };
  17089. checkTypeLambda(thisValue.mType);
  17090. }
  17091. else if (!methodDef->mIsStatic)
  17092. {
  17093. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  17094. {
  17095. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  17096. if (moduleMethodInst)
  17097. {
  17098. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  17099. bool wantsBaseMarking = true;
  17100. if (methodBaseType == mContext->mBfObjectType)
  17101. {
  17102. wantsBaseMarking = false;
  17103. PopulateType(methodBaseType);
  17104. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  17105. {
  17106. if ((fieldInstance.GetFieldDef()->mDeclaringType->IsExtension()) &&
  17107. (fieldInstance.mResolvedType->WantsGCMarking()))
  17108. wantsBaseMarking = true;
  17109. }
  17110. }
  17111. if (wantsBaseMarking)
  17112. {
  17113. auto thisValue = GetThis();
  17114. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  17115. SizedArray<BfIRValue, 1> args;
  17116. if ((!mIsComptimeModule) && (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1)))
  17117. {
  17118. BfExprEvaluator exprEvaluator(this);
  17119. exprEvaluator.SplatArgs(baseValue, args);
  17120. }
  17121. else
  17122. {
  17123. args.push_back(baseValue.mValue);
  17124. }
  17125. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  17126. }
  17127. }
  17128. }
  17129. }
  17130. if (!methodDef->mIsStatic)
  17131. {
  17132. HashSet<int> objectOffsets;
  17133. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  17134. }
  17135. else
  17136. {
  17137. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17138. {
  17139. if (thisValue.IsSplat())
  17140. break;
  17141. auto fieldDef = fieldInst.GetFieldDef();
  17142. if (fieldDef == NULL)
  17143. continue;
  17144. if (fieldInst.mIsThreadLocal)
  17145. continue;
  17146. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  17147. {
  17148. // For extensions, only handle these fields in the appropriate extension
  17149. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17150. continue;
  17151. if (!fieldInst.mFieldIncluded)
  17152. continue;
  17153. auto fieldType = fieldInst.mResolvedType;
  17154. auto fieldDef = fieldInst.GetFieldDef();
  17155. BfTypedValue markVal;
  17156. if (fieldDef->mIsConst)
  17157. continue;
  17158. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17159. continue;
  17160. mBfIRBuilder->PopulateType(fieldType);
  17161. if (fieldType->IsValuelessType())
  17162. continue;
  17163. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  17164. {
  17165. StringT<512> staticVarName;
  17166. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  17167. if (staticVarName.StartsWith('#'))
  17168. continue;
  17169. markVal = ReferenceStaticField(&fieldInst);
  17170. }
  17171. else if (!fieldDef->mIsStatic)
  17172. {
  17173. if (fieldInst.IsAppendedObject())
  17174. {
  17175. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst.mDataIdx);
  17176. auto val = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  17177. markVal = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst.mResolvedType)), fieldInst.mResolvedType);
  17178. }
  17179. else
  17180. {
  17181. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  17182. }
  17183. }
  17184. if (markVal)
  17185. {
  17186. if (fieldInst.IsAppendedObject())
  17187. EmitGCMarkAppended(markVal);
  17188. else
  17189. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  17190. }
  17191. }
  17192. }
  17193. }
  17194. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17195. CallChainedMethods(mCurMethodInstance, false);
  17196. }
  17197. }
  17198. }
  17199. void BfModule::EmitGCFindTLSMembers()
  17200. {
  17201. auto methodDef = mCurMethodInstance->mMethodDef;
  17202. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  17203. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  17204. BF_ASSERT(reportTLSMark);
  17205. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17206. {
  17207. auto fieldDef = fieldInst.GetFieldDef();
  17208. if (fieldDef == NULL)
  17209. continue;
  17210. if (!fieldInst.mIsThreadLocal)
  17211. continue;
  17212. // For extensions, only handle these fields in the appropriate extension
  17213. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17214. continue;
  17215. if (!fieldInst.mFieldIncluded)
  17216. continue;
  17217. if (fieldDef->mIsConst)
  17218. continue;
  17219. auto fieldType = fieldInst.mResolvedType;
  17220. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17221. continue;
  17222. if (fieldType->IsValuelessType())
  17223. continue;
  17224. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  17225. if (markVal)
  17226. {
  17227. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  17228. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  17229. SizedArray<BfIRValue, 2> llvmArgs;
  17230. llvmArgs.push_back(fieldRefPtr);
  17231. llvmArgs.push_back(markFuncPtr);
  17232. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  17233. }
  17234. }
  17235. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17236. CallChainedMethods(mCurMethodInstance, false);
  17237. }
  17238. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup, bool forceIRWrites)
  17239. {
  17240. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  17241. if (mIsComptimeModule)
  17242. {
  17243. BF_ASSERT(!mCompiler->IsAutocomplete());
  17244. }
  17245. if (mAwaitingInitFinish)
  17246. FinishInit();
  17247. if (!methodInstance->mIsReified)
  17248. BF_ASSERT(!mIsReified);
  17249. BF_ASSERT((!methodInstance->GetOwner()->IsUnspecializedTypeVariation()) || (mIsComptimeModule));
  17250. if (methodInstance->mMethodInfoEx != NULL)
  17251. {
  17252. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  17253. {
  17254. if (methodGenericArg->IsMethodRef())
  17255. {
  17256. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  17257. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  17258. }
  17259. }
  17260. }
  17261. if (mBfIRBuilder == NULL)
  17262. {
  17263. BfLogSysM("ProcessMethod %p calling EnsureIRBuilder\n", methodInstance);
  17264. EnsureIRBuilder();
  17265. }
  17266. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, (mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized) && (!forceIRWrites));
  17267. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  17268. {
  17269. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  17270. }
  17271. SetAndRestoreValue<bool> prevIsClassifying;
  17272. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  17273. (mCompiler->mResolvePassData != NULL))
  17274. {
  17275. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  17276. prevIsClassifying.Init(mCompiler->mResolvePassData->mIsClassifying, false);
  17277. }
  17278. if (methodInstance->mHasBeenProcessed)
  17279. {
  17280. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  17281. return;
  17282. }
  17283. if (methodInstance->mFailedConstraints)
  17284. {
  17285. // The only way this should be able to happen is if we fail our generic param check
  17286. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  17287. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  17288. methodInstance->mHasBeenProcessed = true;
  17289. return;
  17290. }
  17291. if (HasExecutedOutput())
  17292. {
  17293. BF_ASSERT(mIsModuleMutable);
  17294. }
  17295. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  17296. if (!mIsComptimeModule)
  17297. {
  17298. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  17299. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  17300. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  17301. {
  17302. auto owningModule = methodInstance->GetOwner()->mModule;
  17303. if (owningModule->mIsScratchModule)
  17304. {
  17305. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  17306. }
  17307. else
  17308. {
  17309. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  17310. if (owningModule->mOnDemandMethodCount > 0)
  17311. owningModule->mOnDemandMethodCount--;
  17312. }
  17313. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  17314. VerifyOnDemandMethods();
  17315. }
  17316. }
  17317. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  17318. // self-referencing append allocations in ctor@calcAppend
  17319. methodInstance->mHasBeenProcessed = true;
  17320. mIncompleteMethodCount--;
  17321. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  17322. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  17323. auto methodDef = methodInstance->mMethodDef;
  17324. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17325. if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  17326. mBfIRBuilder->mIgnoreWrites = true;
  17327. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  17328. {
  17329. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  17330. // so we get the new vdata for it
  17331. methodInstance->GetOwner()->mDirty = true;
  17332. }
  17333. int dependentGenericStartIdx = 0;
  17334. if ((methodDef->mIsLocalMethod) && (mCurMethodState != NULL)) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  17335. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  17336. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  17337. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  17338. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  17339. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  17340. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  17341. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors);
  17342. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, mIsComptimeModule);
  17343. if ((!mIsComptimeModule) && (methodInstance->mIsReified) &&
  17344. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  17345. {
  17346. mCurTypeInstance->mHasBeenInstantiated = true;
  17347. }
  17348. // Warnings are shown in the capture phase
  17349. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  17350. mIgnoreWarnings = true;
  17351. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  17352. UseDefaultSrcPos();
  17353. if ((mIsComptimeModule) && (methodDef->mIsStatic))
  17354. {
  17355. PopulateType(mCurTypeInstance, BfPopulateType_AllowStaticMethods);
  17356. }
  17357. else
  17358. {
  17359. // We may not actually be populated in relatively rare autocompelte cases
  17360. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  17361. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  17362. }
  17363. BfAstNode* nameNode = NULL;
  17364. if (methodDeclaration != NULL)
  17365. {
  17366. nameNode = methodDeclaration->mNameNode;
  17367. if (nameNode == NULL)
  17368. {
  17369. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  17370. nameNode = ctorDeclaration->mThisToken;
  17371. }
  17372. }
  17373. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  17374. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) &&
  17375. (methodDef->mIdx >= 0) && (!methodInstance->mIsForeignMethodDef))
  17376. {
  17377. if (methodInstance->GetExplicitInterface() == NULL)
  17378. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  17379. else
  17380. {
  17381. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  17382. {
  17383. auto ifaceInst = ifaceEntry.mInterfaceType;
  17384. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  17385. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17386. if (methodInstance->GetExplicitInterface() != ifaceInst)
  17387. continue;
  17388. ifaceInst->mTypeDef->PopulateMemberSets();
  17389. BfMethodDef* nextMethod = NULL;
  17390. BfMemberSetEntry* entry = NULL;
  17391. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17392. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17393. while (nextMethod != NULL)
  17394. {
  17395. auto checkMethod = nextMethod;
  17396. nextMethod = nextMethod->mNextWithSameName;
  17397. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  17398. if (implMethodInst == methodInstance)
  17399. {
  17400. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  17401. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  17402. }
  17403. }
  17404. }
  17405. }
  17406. if (methodDef->mIsOverride)
  17407. {
  17408. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  17409. {
  17410. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  17411. if (ventry.mDeclaringMethod.mMethodNum == -1)
  17412. continue;
  17413. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  17414. if (virtMethod != NULL)
  17415. {
  17416. if (virtMethod == methodInstance)
  17417. {
  17418. // Is matching method
  17419. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  17420. {
  17421. auto baseType = mCurTypeInstance->mBaseType;
  17422. if (baseType != NULL)
  17423. {
  17424. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  17425. baseType = baseType->mBaseType;
  17426. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  17427. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  17428. }
  17429. }
  17430. break;
  17431. }
  17432. }
  17433. }
  17434. }
  17435. }
  17436. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d Incomplete:%d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified, mIncompleteMethodCount);
  17437. int importStrNum = -1;
  17438. auto importKind = methodInstance->GetImportKind();
  17439. if ((!mCompiler->mIsResolveOnly) &&
  17440. ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic)))
  17441. {
  17442. if (auto customAttr = methodInstance->GetCustomAttributes()->Get(mCompiler->mImportAttributeTypeDef))
  17443. {
  17444. if (customAttr->mCtorArgs.size() == 1)
  17445. {
  17446. auto fileNameArg = customAttr->mCtorArgs[0];
  17447. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  17448. if (constant != NULL)
  17449. {
  17450. if (!constant->IsNull())
  17451. importStrNum = constant->mInt32;
  17452. }
  17453. else
  17454. {
  17455. importStrNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  17456. }
  17457. if (importStrNum != -1)
  17458. {
  17459. if (!mStringPoolRefs.Contains(importStrNum))
  17460. mStringPoolRefs.Add(importStrNum);
  17461. }
  17462. }
  17463. }
  17464. }
  17465. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  17466. {
  17467. if (mBfIRBuilder->mIgnoreWrites)
  17468. return;
  17469. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  17470. if (!methodInstance->mIRFunction)
  17471. {
  17472. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  17473. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  17474. BF_ASSERT(dllImportGlobalVar || methodInstance->mHasFailed);
  17475. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  17476. }
  17477. if (HasCompiledOutput())
  17478. {
  17479. BfDllImportEntry dllImportEntry;
  17480. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  17481. dllImportEntry.mMethodInstance = mCurMethodInstance;
  17482. mDllImportEntries.push_back(dllImportEntry);
  17483. }
  17484. return;
  17485. }
  17486. StringT<512> mangledName;
  17487. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  17488. if (!methodInstance->mIRFunction)
  17489. {
  17490. bool isIntrinsic = false;
  17491. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  17492. }
  17493. if (methodInstance->mIsIntrinsic)
  17494. return;
  17495. if (mCurTypeInstance->IsFunction())
  17496. return;
  17497. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  17498. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  17499. if (methodDef->mBody != NULL)
  17500. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17501. else if (methodDeclaration != NULL)
  17502. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17503. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17504. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  17505. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17506. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17507. if ((mCurMethodState == NULL) && (!IsInSpecializedSection())) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  17508. {
  17509. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()))
  17510. {
  17511. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(methodDef->mBody))
  17512. sourceClassifier->VisitChildNoRef(methodDef->mBody);
  17513. }
  17514. }
  17515. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  17516. BfMethodState methodState;
  17517. if (mCurMethodState != NULL)
  17518. methodState.mClosureState = mCurMethodState->mClosureState;
  17519. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  17520. {
  17521. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  17522. if (methodInstance->mHotMethod == NULL)
  17523. CheckHotMethod(methodInstance, mangledName);
  17524. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  17525. }
  17526. methodState.mPrevMethodState = mCurMethodState;
  17527. methodState.mMethodInstance = methodInstance;
  17528. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17529. if (methodInstance->GetCustomAttributes() != NULL)
  17530. {
  17531. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  17532. if (typeOptionsIdx != -1)
  17533. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  17534. }
  17535. BfTypeState typeState(mCurTypeInstance);
  17536. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  17537. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  17538. BfMethodInstance* unspecializedMethodInstance = NULL;
  17539. if ((prevMethodState.mPrevVal != NULL) &&
  17540. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  17541. {
  17542. // This is 'inner' (probably a closure) - use binding from outer function
  17543. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  17544. }
  17545. else if ((methodInstance->mIsUnspecialized) ||
  17546. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  17547. {
  17548. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17549. }
  17550. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  17551. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation || mIsComptimeModule) && (!methodInstance->mMethodDef->mIsLocalMethod) && (!methodInstance->mMethodDef->mDeclaringType->IsEmitted()))))
  17552. {
  17553. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  17554. if ((mIsComptimeModule) && (!unspecializedMethodInstance->mHasBeenProcessed))
  17555. {
  17556. // This will have already been populated by CeMachine
  17557. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17558. }
  17559. else
  17560. {
  17561. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  17562. if (!unspecializedMethodInstance->mHasBeenProcessed)
  17563. {
  17564. // Make sure the unspecialized method is processed so we can take its bindings
  17565. // Clear mCurMethodState so we don't think we're in a local method
  17566. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  17567. if (unspecializedMethodInstance->mMethodProcessRequest == NULL)
  17568. unspecializedMethodInstance->mDeclModule->mIncompleteMethodCount++;
  17569. mContext->ProcessMethod(unspecializedMethodInstance);
  17570. }
  17571. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17572. }
  17573. }
  17574. if (methodDef->mMethodType == BfMethodType_Operator)
  17575. {
  17576. auto operatorDef = (BfOperatorDef*) methodDef;
  17577. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  17578. auto paramErrorRefNode = refNode;
  17579. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  17580. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  17581. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  17582. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  17583. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  17584. {
  17585. if (methodDef->mParams.size() != 2)
  17586. {
  17587. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  17588. }
  17589. else
  17590. {
  17591. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17592. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17593. checkParam0 = checkParam0->GetUnderlyingType();
  17594. auto checkParam1 = mCurMethodInstance->GetParamType(1);
  17595. if ((checkParam1->IsRef()) && (!checkParam1->IsOut()))
  17596. checkParam1 = checkParam1->GetUnderlyingType();
  17597. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  17598. (checkParam1 != mCurTypeInstance) && (!checkParam1->IsSelf()))
  17599. {
  17600. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  17601. }
  17602. }
  17603. BfType* wantType = NULL;
  17604. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  17605. {
  17606. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  17607. }
  17608. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  17609. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  17610. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  17611. }
  17612. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  17613. {
  17614. if (methodDef->mIsStatic)
  17615. {
  17616. if (methodDef->mParams.size() != 1)
  17617. {
  17618. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  17619. }
  17620. else
  17621. {
  17622. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17623. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17624. checkParam0 = checkParam0->GetUnderlyingType();
  17625. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()))
  17626. {
  17627. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  17628. }
  17629. }
  17630. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  17631. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  17632. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  17633. {
  17634. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  17635. }
  17636. }
  17637. else
  17638. {
  17639. if (methodDef->mParams.size() != 0)
  17640. {
  17641. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  17642. }
  17643. if (!mCurMethodInstance->mReturnType->IsVoid())
  17644. {
  17645. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  17646. }
  17647. }
  17648. }
  17649. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  17650. {
  17651. if (methodDef->mParams.size() != 1)
  17652. {
  17653. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  17654. }
  17655. if (!mCurMethodInstance->mReturnType->IsVoid())
  17656. {
  17657. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  17658. }
  17659. }
  17660. else // Conversion
  17661. {
  17662. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  17663. {
  17664. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  17665. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  17666. }
  17667. if (methodDef->mParams.size() != 1)
  17668. {
  17669. auto refNode = paramErrorRefNode;
  17670. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  17671. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  17672. Fail("Conversion operators must declare one parameter", refNode);
  17673. }
  17674. else if ((methodInstance->mMethodInfoEx == NULL) ||
  17675. (methodInstance->mMethodInfoEx->mMethodGenericArguments.IsEmpty()) ||
  17676. ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation)))
  17677. {
  17678. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17679. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17680. checkParam0 = checkParam0->GetUnderlyingType();
  17681. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  17682. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  17683. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  17684. if (checkParam0 == mCurMethodInstance->mReturnType)
  17685. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  17686. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  17687. // happened here
  17688. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (checkParam0 != mContext->mBfObjectType)))
  17689. {
  17690. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  17691. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, checkParam0->ToTypeInstance());
  17692. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  17693. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  17694. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  17695. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  17696. }
  17697. }
  17698. }
  17699. }
  17700. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mBfIRBuilder->mIgnoreWrites) && (mHasFullDebugInfo);
  17701. if (methodDef->mMethodType == BfMethodType_Mixin)
  17702. wantsDIData = false;
  17703. if (mCurTypeInstance->IsUnspecializedType())
  17704. wantsDIData = false;
  17705. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  17706. wantsDIData = false;
  17707. bool wantsDIVariables = wantsDIData;
  17708. if (methodDef->mIsExtern)
  17709. wantsDIVariables = false;
  17710. SizedArray<BfIRMDNode, 8> diParams;
  17711. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  17712. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  17713. BfType* thisType = NULL;
  17714. if (!methodDef->mIsStatic)
  17715. {
  17716. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  17717. thisType = methodState.mClosureState->mClosureType;
  17718. else
  17719. thisType = mCurTypeInstance;
  17720. }
  17721. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  17722. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  17723. //////////////////////////////////////////////////////////////////////////
  17724. //
  17725. {
  17726. if (methodDeclaration != NULL)
  17727. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17728. else if (methodDef->mBody != NULL)
  17729. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17730. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17731. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  17732. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17733. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17734. }
  17735. BfIRMDNode diFunction;
  17736. if (wantsDIData)
  17737. {
  17738. BP_ZONE("BfModule::DoMethodDeclaration.DISetup");
  17739. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  17740. int defLine = mCurFilePosition.mCurLine;
  17741. if (mDICompileUnit)
  17742. {
  17743. int flags = 0;
  17744. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  17745. if (methodDef->mProtection == BfProtection_Public)
  17746. flags = llvm::DINode::FlagPublic;
  17747. else if (methodDef->mProtection == BfProtection_Protected)
  17748. flags = llvm::DINode::FlagProtected;
  17749. else
  17750. flags = llvm::DINode::FlagPrivate;
  17751. if (methodDef->mIsOverride)
  17752. {
  17753. //flags |= llvm::DINode::FlagVirtual;
  17754. }
  17755. else if (methodDef->mIsVirtual)
  17756. flags |= llvm::DINode::FlagIntroducedVirtual;
  17757. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  17758. flags |= llvm::DINode::FlagStaticMember;
  17759. else
  17760. {
  17761. if ((mCurTypeInstance->IsValuelessType()) ||
  17762. ((!mIsComptimeModule) && (mCurTypeInstance->IsSplattable())))
  17763. flags |= llvm::DINode::FlagStaticMember;
  17764. }
  17765. flags |= llvm::DINode::FlagPrototyped;
  17766. if (methodDef->mMethodType == BfMethodType_Ctor)
  17767. {
  17768. flags |= llvm::DINode::FlagArtificial;
  17769. }
  17770. auto llvmFunction = methodInstance->mIRFunction;
  17771. SizedArray<BfIRMDNode, 1> genericArgs;
  17772. SizedArray<BfIRValue, 1> genericConstValueArgs;
  17773. String methodName;
  17774. if (methodInstance->GetForeignType() != NULL)
  17775. {
  17776. methodName += TypeToString(methodInstance->GetForeignType());
  17777. methodName += ".";
  17778. }
  17779. if (methodInstance->GetExplicitInterface() != NULL)
  17780. {
  17781. methodName += TypeToString(methodInstance->GetExplicitInterface());
  17782. methodName += ".";
  17783. }
  17784. methodName += methodDef->mName;
  17785. if (methodInstance->GetNumGenericArguments() != 0)
  17786. {
  17787. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  17788. {
  17789. if (genericArg->IsConstExprValue())
  17790. {
  17791. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  17792. while (genericConstValueArgs.size() < genericArgs.size())
  17793. genericConstValueArgs.push_back(BfIRValue());
  17794. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  17795. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  17796. }
  17797. else
  17798. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  17799. }
  17800. methodName += "<";
  17801. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  17802. {
  17803. if (i > 0)
  17804. methodName += ", ";
  17805. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  17806. methodName += TypeToString(type);
  17807. }
  17808. methodName += ">";
  17809. }
  17810. if ((methodName.empty()) && (methodDeclaration != NULL))
  17811. {
  17812. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  17813. {
  17814. methodName += "operator";
  17815. if (operatorDecl->mIsConvOperator)
  17816. {
  17817. methodName += " ";
  17818. methodName += TypeToString(methodInstance->mReturnType);
  17819. }
  17820. else if (operatorDecl->mOpTypeToken != NULL)
  17821. methodName += operatorDecl->mOpTypeToken->ToString();
  17822. }
  17823. }
  17824. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  17825. methodName += "$CHK";
  17826. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  17827. methodName += "$UCHK";
  17828. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  17829. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  17830. // defLine + 1, diFuncType, false, true,
  17831. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  17832. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  17833. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  17834. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  17835. defLine + 1, diFuncType, false, true,
  17836. llvm::dwarf::DW_VIRTUALITY_none,
  17837. 0,
  17838. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  17839. }
  17840. else
  17841. {
  17842. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  17843. }
  17844. }
  17845. //////////////////////////////////////////////////////////////////////////
  17846. // Head and Init get rolled into Entry afterwards.
  17847. methodState.mIRFunction = methodInstance->mIRFunction;
  17848. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  17849. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  17850. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  17851. methodState.mCurScope->mDIScope = diFunction;
  17852. auto llvmEntryBlock = methodState.mIREntryBlock;
  17853. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  17854. if (methodDef->mName == "__MALFORMED")
  17855. {
  17856. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  17857. mBfIRBuilder->SetInsertPoint(newBlock);
  17858. }
  17859. if (methodDef->mBody != NULL)
  17860. {
  17861. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17862. }
  17863. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  17864. {
  17865. // We want to be able to step into delegate invokes -- we actually step over them
  17866. if (methodDef->mName != "Invoke")
  17867. {
  17868. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  17869. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  17870. }
  17871. }
  17872. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  17873. mBfIRBuilder->ClearDebugLocation();
  17874. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  17875. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  17876. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  17877. {
  17878. int localIdx = 0;
  17879. int argIdx = 0;
  17880. Array<BfIRValue> splatAddrValues;
  17881. for ( ; argIdx < irParamCount; localIdx++)
  17882. {
  17883. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  17884. if ((isThis) && (thisType->IsValuelessType()))
  17885. isThis = false;
  17886. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() == argIdx))
  17887. {
  17888. argIdx++;
  17889. if (argIdx == irParamCount)
  17890. break;
  17891. }
  17892. BfLocalVariable* paramVar = NULL;
  17893. while (true)
  17894. {
  17895. BF_ASSERT(localIdx < methodState.mLocals.size());
  17896. paramVar = methodState.mLocals[localIdx];
  17897. if ((paramVar->mCompositeCount == -1) &&
  17898. (!paramVar->mIsConst) &&
  17899. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  17900. break;
  17901. localIdx++;
  17902. }
  17903. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  17904. {
  17905. paramVar->mIsReadOnly = true;
  17906. }
  17907. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) ||
  17908. ((!mIsComptimeModule) && (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter)));
  17909. if (paramVar->mResolvedType->IsMethodRef())
  17910. wantsAddr = false;
  17911. // if ((methodDef->mHasAppend) && (argIdx == 1))
  17912. // {
  17913. // BF_ASSERT(paramVar->mName == "appendIdx");
  17914. // wantsAddr = true;
  17915. // }
  17916. if (paramVar->mIsSplat)
  17917. {
  17918. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  17919. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  17920. BfTypeUtils::SplatIterate([&](BfType* checkType)
  17921. {
  17922. BfIRType splatIRType;
  17923. if (checkType->IsComposite())
  17924. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  17925. else
  17926. splatIRType = mBfIRBuilder->MapType(checkType);
  17927. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  17928. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  17929. if (!paramVar->mAddr)
  17930. paramVar->mAddr = allocaInst;
  17931. if (WantsLifetimes())
  17932. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  17933. splatAddrValues.push_back(allocaInst);
  17934. }, paramVar->mResolvedType);
  17935. mBfIRBuilder->SetInsertPoint(prevInsert);
  17936. }
  17937. else if (isThis)
  17938. {
  17939. if (wantsAddr)
  17940. {
  17941. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  17942. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  17943. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  17944. if (paramVar->mIsSplat)
  17945. {
  17946. //
  17947. }
  17948. else
  17949. {
  17950. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  17951. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  17952. wantPtr = true;
  17953. if (wantPtr)
  17954. {
  17955. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  17956. }
  17957. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  17958. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  17959. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  17960. paramVar->mAddr = allocaInst;
  17961. if (WantsLifetimes())
  17962. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  17963. }
  17964. mBfIRBuilder->SetInsertPoint(prevInsert);
  17965. }
  17966. }
  17967. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  17968. {
  17969. // Address doesn't change so we don't have to alloca it
  17970. BfIRType allocType;
  17971. int alignSize = mSystem->mPtrSize;
  17972. if (paramVar->mResolvedType->IsRef())
  17973. {
  17974. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  17975. }
  17976. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  17977. {
  17978. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  17979. alignSize = paramVar->mResolvedType->mAlign;
  17980. }
  17981. else
  17982. {
  17983. paramVar->mHasLocalStructBacking = true;
  17984. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  17985. if (typeInst != NULL)
  17986. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  17987. else
  17988. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  17989. }
  17990. if (wantsAddr)
  17991. {
  17992. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  17993. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  17994. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  17995. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  17996. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  17997. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  17998. paramVar->mAddr = allocaInst;
  17999. mBfIRBuilder->SetInsertPoint(prevInsert);
  18000. if (WantsLifetimes())
  18001. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18002. }
  18003. }
  18004. else if (wantsAddr)
  18005. {
  18006. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  18007. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18008. paramVar->mAddr = allocaInst;
  18009. }
  18010. if (paramVar->mIsSplat)
  18011. {
  18012. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18013. }
  18014. else if (paramVar->mIsLowered)
  18015. {
  18016. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18017. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18018. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18019. argIdx++;
  18020. if (loweredTypeCode2 != BfTypeCode_None)
  18021. argIdx++;
  18022. }
  18023. else
  18024. {
  18025. argIdx++;
  18026. }
  18027. }
  18028. if (methodDef->mBody != NULL)
  18029. UpdateSrcPos(methodDef->mBody);
  18030. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18031. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18032. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18033. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  18034. localIdx = 0;
  18035. argIdx = 0;
  18036. int splatAddrIdx = 0;
  18037. while (localIdx < (int)methodState.mLocals.size())
  18038. {
  18039. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  18040. argIdx++;
  18041. int curLocalIdx = localIdx++;
  18042. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  18043. if (paramVar->mIsConst)
  18044. continue;
  18045. if (!paramVar->IsParam())
  18046. continue;
  18047. if (paramVar->mCompositeCount != -1)
  18048. continue;
  18049. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18050. if ((isThis) && (thisType->IsValuelessType()))
  18051. isThis = false;
  18052. if (paramVar->mValue.IsArg())
  18053. BF_ASSERT(paramVar->mValue.mId == argIdx);
  18054. BfIRMDNode diVariable;
  18055. if (wantsDIData)
  18056. {
  18057. String paramName = paramVar->mName;
  18058. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18059. if (isThis)
  18060. {
  18061. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  18062. paramName = "__closure";
  18063. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18064. {
  18065. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18066. bool wantRef = paramVar->mResolvedType->IsComposite();
  18067. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  18068. wantRef = true;
  18069. if (wantRef)
  18070. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18071. }
  18072. else if (!paramVar->mResolvedType->IsValueType())
  18073. {
  18074. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  18075. }
  18076. }
  18077. else
  18078. {
  18079. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18080. {
  18081. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18082. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18083. diType = mBfIRBuilder->DbgCreateConstType(diType);
  18084. }
  18085. }
  18086. if (!paramVar->mIsSplat)
  18087. {
  18088. if ((paramVar->mParamIdx >= 0) && (paramVar->mParamIdx < methodInstance->mDefaultValues.mSize))
  18089. {
  18090. auto defaultValue = methodInstance->mDefaultValues[paramVar->mParamIdx];
  18091. auto constant = mCurTypeInstance->mConstHolder->GetConstant(defaultValue.mValue);
  18092. if ((constant != NULL) &&
  18093. ((BfIRConstHolder::IsIntable(constant->mTypeCode)) || (BfIRConstHolder::IsFloat(constant->mTypeCode))))
  18094. {
  18095. int64 writeVal = constant->mInt64;
  18096. if (constant->mTypeCode == BfTypeCode_Float)
  18097. {
  18098. // We need to do this because Singles are stored in mDouble, so we need to reduce here
  18099. float floatVal = (float)constant->mDouble;
  18100. writeVal = *(uint32*)&floatVal;
  18101. }
  18102. if (writeVal < 0)
  18103. paramName += StrFormat("$_%llu", -writeVal);
  18104. else
  18105. paramName += StrFormat("$%llu", writeVal);
  18106. }
  18107. }
  18108. if (paramVar->mResolvedType->IsValuelessType())
  18109. {
  18110. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  18111. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18112. }
  18113. else if (paramVar->mIsImplicitParam)
  18114. {
  18115. // Annotate this specially?
  18116. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18117. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18118. }
  18119. else
  18120. {
  18121. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18122. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18123. }
  18124. paramVar->mDbgVarInst = diVariable;
  18125. }
  18126. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  18127. {
  18128. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  18129. // {
  18130. // // Only add this placeholder if we don't have any values
  18131. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  18132. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18133. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  18134. // }
  18135. }
  18136. }
  18137. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  18138. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  18139. {
  18140. // Write our argument value into the .addr
  18141. mBfIRBuilder->ClearDebugLocation();
  18142. if (paramVar->mIsSplat)
  18143. {
  18144. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18145. //
  18146. }
  18147. else
  18148. {
  18149. bool handled = false;
  18150. if (paramVar->mIsLowered)
  18151. {
  18152. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18153. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18154. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  18155. {
  18156. BfIRValue targetAddr = paramVar->mAddr;
  18157. bool isTempTarget = false;
  18158. int loweredSize = mBfIRBuilder->GetSize(loweredTypeCode) + mBfIRBuilder->GetSize(loweredTypeCode2);
  18159. if (paramVar->mResolvedType->mSize < loweredSize)
  18160. {
  18161. isTempTarget = true;
  18162. targetAddr = CreateAlloca(GetPrimitiveType(BfTypeCode_Int8), true, NULL, GetConstValue(loweredSize));
  18163. mBfIRBuilder->SetAllocaAlignment(targetAddr,
  18164. BF_MAX(paramVar->mResolvedType->mAlign,
  18165. BF_MAX(mBfIRBuilder->GetSize(loweredTypeCode), mBfIRBuilder->GetSize(loweredTypeCode2))));
  18166. }
  18167. // We have a lowered type coming in, so we have to cast the .addr before storing
  18168. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  18169. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  18170. auto primPtrVal = mBfIRBuilder->CreateBitCast(targetAddr, primPtrType);
  18171. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, mCurTypeInstance->mAlign);
  18172. if (loweredTypeCode2 != BfTypeCode_None)
  18173. {
  18174. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  18175. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  18176. BfIRValue primPtrVal2;
  18177. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  18178. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  18179. else
  18180. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  18181. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  18182. }
  18183. if (isTempTarget)
  18184. {
  18185. auto castedTempPtr = mBfIRBuilder->CreateBitCast(targetAddr, mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType)));
  18186. auto tempVal = mBfIRBuilder->CreateAlignedLoad(castedTempPtr, paramVar->mResolvedType->mAlign);
  18187. mBfIRBuilder->CreateAlignedStore(tempVal, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  18188. }
  18189. // We don't want to allow directly using value
  18190. paramVar->mValue = BfIRValue();
  18191. handled = true;
  18192. }
  18193. else
  18194. {
  18195. BF_ASSERT("Expected lowered");
  18196. }
  18197. }
  18198. if (!handled)
  18199. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  18200. }
  18201. }
  18202. if (methodDef->mBody != NULL)
  18203. UpdateSrcPos(methodDef->mBody);
  18204. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  18205. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  18206. else if (methodDeclaration == NULL)
  18207. UseDefaultSrcPos();
  18208. // Write our argument value into the .addr
  18209. if (paramVar->mIsSplat)
  18210. {
  18211. int splatComponentIdx = 0;
  18212. auto curArgIdx = argIdx;
  18213. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  18214. {
  18215. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  18216. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  18217. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  18218. mBfIRBuilder->ClearDebugLocation(storeInst);
  18219. if (wantsDIData)
  18220. {
  18221. BfIRMDNode diType;
  18222. if (checkType->IsComposite())
  18223. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  18224. else
  18225. diType = mBfIRBuilder->DbgGetType(checkType);
  18226. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18227. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18228. if (wantsDIVariables)
  18229. {
  18230. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  18231. }
  18232. }
  18233. curArgIdx++;
  18234. splatComponentIdx++;
  18235. };
  18236. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  18237. {
  18238. if (checkType->IsStruct())
  18239. {
  18240. auto checkTypeInstance = checkType->ToTypeInstance();
  18241. if (checkTypeInstance->mBaseType != NULL)
  18242. {
  18243. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  18244. }
  18245. if (checkTypeInstance->mIsUnion)
  18246. {
  18247. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  18248. if (!unionInnerType->IsValuelessType())
  18249. {
  18250. _FinishSplatsIterate(unionInnerType, name + "$u");
  18251. }
  18252. if (checkTypeInstance->IsEnum())
  18253. {
  18254. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  18255. _FinishSplatsIterate(dscrType, name + "$d");
  18256. }
  18257. }
  18258. else
  18259. {
  18260. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  18261. {
  18262. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  18263. auto fieldDef = fieldInstance->GetFieldDef();
  18264. if (fieldInstance->mDataIdx >= 0)
  18265. {
  18266. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  18267. }
  18268. }
  18269. }
  18270. }
  18271. else if (checkType->IsMethodRef())
  18272. {
  18273. auto methodRefType = (BfMethodRefType*)checkType;
  18274. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  18275. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  18276. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  18277. // {
  18278. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  18279. // if (!paramType->IsValuelessType())
  18280. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  18281. // }
  18282. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  18283. {
  18284. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  18285. String paramName = methodInstance->GetParamName(paramIdx);
  18286. if (paramName == "this")
  18287. paramName = "__this";
  18288. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  18289. {
  18290. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  18291. }
  18292. else
  18293. {
  18294. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  18295. }
  18296. }
  18297. }
  18298. else if (!checkType->IsValuelessType())
  18299. {
  18300. _FinishSplats(checkType, name);
  18301. }
  18302. };
  18303. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18304. if (!paramVar->mConstValue)
  18305. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  18306. }
  18307. BfIRValue declareCall;
  18308. if (diVariable)
  18309. {
  18310. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  18311. {
  18312. if (!paramVar->mAddr)
  18313. {
  18314. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  18315. {
  18316. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  18317. {
  18318. // We don't need to set the location for this
  18319. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  18320. }
  18321. }
  18322. else
  18323. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  18324. }
  18325. else
  18326. {
  18327. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  18328. }
  18329. }
  18330. }
  18331. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  18332. {
  18333. // We don't allow actually assignment to "this", so we just do a single load
  18334. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  18335. // we need to store it in the stack frame for debugging purposes
  18336. auto loadedThis = mBfIRBuilder->CreateAlignedLoad(paramVar->mAddr/*, "this"*/, paramVar->mResolvedType->mAlign);
  18337. mBfIRBuilder->ClearDebugLocation(loadedThis);
  18338. paramVar->mValue = loadedThis;
  18339. }
  18340. if ((wantsDIData) && (declareCall))
  18341. mBfIRBuilder->UpdateDebugLocation(declareCall);
  18342. if (paramVar->mIsSplat)
  18343. {
  18344. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18345. }
  18346. else if (paramVar->mIsLowered)
  18347. {
  18348. argIdx++;
  18349. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18350. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18351. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18352. if (loweredTypeCode2 != BfTypeCode_None)
  18353. argIdx++;
  18354. }
  18355. else if (!paramVar->mResolvedType->IsValuelessType())
  18356. {
  18357. argIdx++;
  18358. }
  18359. }
  18360. if (wantsDIData)
  18361. {
  18362. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  18363. }
  18364. }
  18365. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  18366. {
  18367. auto paramVar = mCurMethodState->mLocals[varIdx];
  18368. // We don't need this because the debug func type records the type of the splat param, and then the same can be inferred from the first
  18369. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  18370. // if (paramVar->mIsSplat)
  18371. // {
  18372. // if (wantsDIVariables)
  18373. // {
  18374. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  18375. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  18376. // }
  18377. // }
  18378. if (paramVar->mResolvedType->IsValuelessType())
  18379. {
  18380. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  18381. {
  18382. // Only add this placeholder if we don't have any values
  18383. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18384. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  18385. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18386. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  18387. }
  18388. }
  18389. }
  18390. if (IsTargetingBeefBackend())
  18391. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  18392. if (methodState.mClosureState != NULL)
  18393. {
  18394. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  18395. {
  18396. BfLocalVariable* localVar = new BfLocalVariable();
  18397. *localVar = constLocal;
  18398. localVar->mIsBumpAlloc = false;
  18399. AddLocalVariableDef(localVar, true);
  18400. }
  18401. }
  18402. bool wantsRemoveBody = false;
  18403. bool skipBody = false;
  18404. bool skipUpdateSrcPos = false;
  18405. bool skipEndChecks = false;
  18406. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  18407. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18408. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  18409. hasExternSpecifier = true;
  18410. // Allocate, clear, set classVData
  18411. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  18412. {
  18413. CreateStaticCtor();
  18414. }
  18415. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  18416. {
  18417. skipBody = true;
  18418. skipEndChecks = true;
  18419. if (HasExecutedOutput())
  18420. {
  18421. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18422. mBfIRBuilder->ClearDebugLocation();
  18423. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  18424. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  18425. PopulateType(innerType, BfPopulateType_DataAndMethods);
  18426. mBfIRBuilder->PopulateType(mCurTypeInstance);
  18427. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  18428. if (methodInstance->mIsForeignMethodDef)
  18429. {
  18430. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  18431. }
  18432. BfTypeVector methodGenericArguments;
  18433. if (methodInstance->mMethodInfoEx != NULL)
  18434. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  18435. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  18436. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  18437. {
  18438. if (!methodInstance->mReturnType->IsValuelessType())
  18439. {
  18440. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  18441. CreateReturn(retVal);
  18442. }
  18443. else
  18444. mBfIRBuilder->CreateRetVoid();
  18445. }
  18446. else
  18447. {
  18448. auto innerMethodDef = innerMethodInstance.mMethodInstance->mMethodDef;
  18449. BF_ASSERT(innerMethodDef == methodDef);
  18450. SizedArray<BfIRValue, 8> innerParams;
  18451. BfExprEvaluator exprEvaluator(this);
  18452. if (!innerType->IsValuelessType())
  18453. {
  18454. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  18455. BfTypedValue innerVal(thisValue, innerType, true);
  18456. if (boxedType->IsBoxedStructPtr())
  18457. {
  18458. innerVal = LoadValue(innerVal);
  18459. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  18460. }
  18461. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  18462. }
  18463. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  18464. {
  18465. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  18466. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  18467. exprEvaluator.PushArg(localVal, innerParams);
  18468. }
  18469. if (!innerMethodInstance.mFunc)
  18470. {
  18471. BF_ASSERT(innerType->IsUnspecializedType());
  18472. }
  18473. else if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  18474. {
  18475. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  18476. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  18477. exprEvaluator.mReceivingValue = &returnType;
  18478. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  18479. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  18480. mBfIRBuilder->CreateRetVoid();
  18481. }
  18482. else
  18483. {
  18484. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  18485. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  18486. if (mCurMethodInstance->mReturnType->IsValueType())
  18487. retVal = LoadValue(retVal);
  18488. CreateReturn(retVal.mValue);
  18489. }
  18490. }
  18491. }
  18492. mCurMethodState->SetHadReturn(true);
  18493. mCurMethodState->mLeftBlockUncond = true;
  18494. }
  18495. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  18496. {
  18497. SetIllegalSrcPos();
  18498. mBfIRBuilder->ClearDebugLocation();
  18499. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  18500. auto thisVal = GetThis();
  18501. int prevSize = 0;
  18502. if (mContext->mBfObjectType != NULL)
  18503. {
  18504. prevSize = mContext->mBfObjectType->mInstSize;
  18505. PopulateType(mContext->mBfObjectType);
  18506. // If we have object extensions, clear out starting at the extension
  18507. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  18508. {
  18509. if (fieldInstance.GetFieldDef()->mDeclaringType->IsExtension())
  18510. {
  18511. prevSize = fieldInstance.mDataOffset;
  18512. break;
  18513. }
  18514. }
  18515. }
  18516. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  18517. int curSize = mCurTypeInstance->mInstSize;
  18518. if (curSize > prevSize)
  18519. {
  18520. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  18521. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  18522. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  18523. }
  18524. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  18525. {
  18526. auto useThis = mCurMethodState->mLocals[0]->mValue;
  18527. auto useThisType = mCurTypeInstance;
  18528. auto checkTypeInst = mCurTypeInstance;
  18529. while (checkTypeInst != NULL)
  18530. {
  18531. for (auto& fieldInstance : checkTypeInst->mFieldInstances)
  18532. {
  18533. auto fieldDef = fieldInstance.GetFieldDef();
  18534. if ((fieldDef == NULL) || (fieldDef->mIsStatic))
  18535. continue;
  18536. if (fieldInstance.IsAppendedObject())
  18537. {
  18538. if (checkTypeInst != useThisType)
  18539. {
  18540. useThis = mBfIRBuilder->CreateBitCast(useThis, mBfIRBuilder->MapType(checkTypeInst));
  18541. useThisType = checkTypeInst;
  18542. }
  18543. BfIRValue fieldAddr = mBfIRBuilder->CreateInBoundsGEP(useThis, 0, fieldInstance.mDataIdx);
  18544. auto int8PtrVal = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(int8PtrType));
  18545. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  18546. }
  18547. }
  18548. checkTypeInst = checkTypeInst->mBaseType;
  18549. }
  18550. }
  18551. skipUpdateSrcPos = true;
  18552. }
  18553. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  18554. {
  18555. EmitCtorBody(skipBody);
  18556. }
  18557. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  18558. {
  18559. EmitDtorBody();
  18560. skipBody = true;
  18561. }
  18562. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  18563. {
  18564. EmitIteratorBlock(skipBody);
  18565. }
  18566. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  18567. {
  18568. // We need to be able to mark deleted objects
  18569. mCurMethodState->mIgnoreObjectAccessCheck = true;
  18570. }
  18571. auto customAttributes = methodInstance->GetCustomAttributes();
  18572. if (customAttributes != NULL)
  18573. {
  18574. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  18575. mCurMethodState->mIgnoreObjectAccessCheck = true;
  18576. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  18577. mCurMethodState->mDisableChecks = true;
  18578. }
  18579. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  18580. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  18581. {
  18582. // We chain even non-default ctors to the default ctors
  18583. auto defaultCtor = methodInstance;
  18584. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  18585. CallChainedMethods(defaultCtor, false);
  18586. }
  18587. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  18588. if (!mCompiler->mHasRequiredTypes)
  18589. {
  18590. // Skip processing to avoid errors
  18591. }
  18592. else if (methodDef->mBody == NULL)
  18593. {
  18594. if (methodDeclaration != NULL)
  18595. {
  18596. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18597. {
  18598. if (operatorDeclaration->mIsConvOperator)
  18599. wantsRemoveBody = true;
  18600. }
  18601. }
  18602. bool isDllImport = false;
  18603. if ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic))
  18604. {
  18605. if (importStrNum != -1)
  18606. {
  18607. if (importKind == BfImportKind_Import_Static)
  18608. {
  18609. if (!mImportFileNames.Contains(importStrNum))
  18610. {
  18611. mImportFileNames.Add(importStrNum);
  18612. }
  18613. }
  18614. }
  18615. }
  18616. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  18617. {
  18618. CreateDllImportMethod();
  18619. }
  18620. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  18621. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  18622. {
  18623. if (mCurTypeInstance->mTypeDef->mIsFunction)
  18624. {
  18625. // Emit nothing
  18626. }
  18627. else
  18628. {
  18629. CreateDelegateInvokeMethod();
  18630. mCurMethodState->SetHadReturn(true);
  18631. mCurMethodState->mLeftBlockUncond = true;
  18632. }
  18633. }
  18634. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  18635. {
  18636. if (mCurTypeInstance->IsObject())
  18637. {
  18638. CreateDynamicCastMethod();
  18639. }
  18640. else
  18641. {
  18642. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  18643. mCurMethodState->mHadReturn = true;
  18644. }
  18645. }
  18646. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  18647. {
  18648. BfIRValue ret;
  18649. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  18650. {
  18651. // This can happen if we provide an invalid name
  18652. AssertErrorState();
  18653. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  18654. }
  18655. else
  18656. {
  18657. // Unfortunate DebugLoc shenanigans-
  18658. // Our params get removed if we don't have any DebugLocs, but we don't want to actually be able to step into this method,
  18659. // so we only set the loc on the CreateRet which gets inlined out
  18660. mBfIRBuilder->SaveDebugLocation();
  18661. mBfIRBuilder->ClearDebugLocation();
  18662. BfIRValue fromBool;
  18663. if (!mCurTypeInstance->IsTypedPrimitive())
  18664. {
  18665. fromBool = GetDefaultValue(methodInstance->mReturnType);
  18666. }
  18667. else
  18668. {
  18669. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  18670. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  18671. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  18672. }
  18673. mBfIRBuilder->RestoreDebugLocation();
  18674. ret = mBfIRBuilder->CreateRet(fromBool);
  18675. //ExtendLocalLifetimes(0);
  18676. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18677. }
  18678. mCurMethodState->SetHadReturn(true);
  18679. mCurMethodState->mLeftBlockUncond = true;
  18680. }
  18681. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  18682. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  18683. {
  18684. BfIRValue ret;
  18685. // Unfortunate DebugLoc shenanigans-
  18686. // Our params get removed if we don't have any DebugLocs, but we don't want to actually be able to step into this method,
  18687. // so we only set the loc on the CreateRet which gets inlined out
  18688. mBfIRBuilder->SaveDebugLocation();
  18689. mBfIRBuilder->ClearDebugLocation();
  18690. BfIRValue fromBool;
  18691. mBfIRBuilder->RestoreDebugLocation();
  18692. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  18693. //ExtendLocalLifetimes(0);
  18694. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18695. mCurMethodState->SetHadReturn(true);
  18696. mCurMethodState->mLeftBlockUncond = true;
  18697. }
  18698. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  18699. {
  18700. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  18701. if (HasExecutedOutput())
  18702. {
  18703. EmitEnumToStringBody();
  18704. }
  18705. mBfIRBuilder->CreateRetVoid();
  18706. mCurMethodState->SetHadReturn(true);
  18707. mCurMethodState->mLeftBlockUncond = true;
  18708. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18709. }
  18710. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  18711. {
  18712. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  18713. if (HasExecutedOutput())
  18714. {
  18715. EmitTupleToStringBody();
  18716. }
  18717. mBfIRBuilder->CreateRetVoid();
  18718. mCurMethodState->SetHadReturn(true);
  18719. mCurMethodState->mLeftBlockUncond = true;
  18720. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18721. }
  18722. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  18723. {
  18724. CreateValueTypeEqualsMethod(false);
  18725. skipBody = true;
  18726. skipEndChecks = true;
  18727. }
  18728. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  18729. {
  18730. CreateValueTypeEqualsMethod(true);
  18731. skipBody = true;
  18732. skipEndChecks = true;
  18733. }
  18734. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef->GetDefinition() == mCompiler->mValueTypeTypeDef))
  18735. {
  18736. CreateValueTypeEqualsMethod(false);
  18737. skipBody = true;
  18738. skipEndChecks = true;
  18739. }
  18740. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (mCurTypeInstance->IsDelegate()))
  18741. {
  18742. CreateDelegateEqualsMethod();
  18743. skipBody = true;
  18744. skipEndChecks = true;
  18745. }
  18746. else
  18747. {
  18748. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18749. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  18750. {
  18751. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  18752. Fail("Body expected", methodDef->mBody);
  18753. }
  18754. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  18755. {
  18756. if ((methodInstance->mReturnType->IsRef()) && (!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  18757. Fail("Auto-implemented ref property getters must declare 'mut'", methodInstance->mMethodDef->GetRefNode());
  18758. if (methodInstance->mReturnType->IsValuelessType())
  18759. {
  18760. mBfIRBuilder->CreateRetVoid();
  18761. }
  18762. else if (HasExecutedOutput())
  18763. {
  18764. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  18765. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  18766. BfFieldDef* fieldDef = NULL;
  18767. if (fieldInstance != NULL)
  18768. fieldDef = fieldInstance->GetFieldDef();
  18769. BfType* retType = methodInstance->mReturnType;
  18770. if (retType->IsRef())
  18771. retType = retType->GetUnderlyingType();
  18772. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  18773. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  18774. {
  18775. BfTypedValue lookupValue;
  18776. if (fieldDef->IsNonConstStatic())
  18777. lookupValue = ReferenceStaticField(fieldInstance);
  18778. else if (mCurTypeInstance->IsObject())
  18779. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  18780. else
  18781. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  18782. if (methodInstance->mReturnType->IsRef())
  18783. {
  18784. if ((!lookupValue.IsAddr()) && (!lookupValue.mType->IsValuelessType()))
  18785. lookupValue = MakeAddressable(lookupValue);
  18786. }
  18787. else
  18788. lookupValue = LoadOrAggregateValue(lookupValue);
  18789. CreateReturn(lookupValue.mValue);
  18790. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18791. }
  18792. else
  18793. {
  18794. // This can happen if we have two properties with the same name but different types
  18795. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  18796. EmitDefaultReturn();
  18797. }
  18798. }
  18799. else
  18800. {
  18801. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  18802. EmitDefaultReturn();
  18803. }
  18804. mCurMethodState->SetHadReturn(true);
  18805. }
  18806. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  18807. {
  18808. if ((!methodDef->mIsMutating) && (!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  18809. {
  18810. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  18811. }
  18812. else if (!mCompiler->IsAutocomplete())
  18813. {
  18814. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  18815. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  18816. auto fieldDef = fieldInstance->GetFieldDef();
  18817. auto& lastParam = mCurMethodState->mLocals.back();
  18818. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  18819. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  18820. {
  18821. BfIRValue lookupAddr;
  18822. if (fieldDef->IsNonConstStatic())
  18823. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  18824. else
  18825. {
  18826. auto thisValue = GetThis();
  18827. if (thisValue.IsSplat())
  18828. {
  18829. BFMODULE_FATAL(this, "Should not happen");
  18830. }
  18831. if (mCurTypeInstance->IsObject())
  18832. thisValue = LoadValue(thisValue);
  18833. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  18834. }
  18835. BfExprEvaluator exprEvaluator(this);
  18836. auto localVal = exprEvaluator.LoadLocal(lastParam);
  18837. localVal = LoadOrAggregateValue(localVal);
  18838. if (!localVal.mType->IsValuelessType())
  18839. mBfIRBuilder->CreateAlignedStore(localVal.mValue, lookupAddr, localVal.mType->mAlign);
  18840. }
  18841. else if (!fieldInstance->mResolvedType->IsValuelessType())
  18842. {
  18843. // This can happen if we have two properties with the same name but different types
  18844. AssertErrorState();
  18845. }
  18846. }
  18847. }
  18848. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  18849. {
  18850. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  18851. {
  18852. if (HasCompiledOutput())
  18853. EmitGCMarkMembers();
  18854. }
  18855. else if (!mCurTypeInstance->IsObject())
  18856. {
  18857. }
  18858. }
  18859. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  18860. {
  18861. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  18862. {
  18863. if (HasCompiledOutput())
  18864. EmitGCFindTLSMembers();
  18865. }
  18866. }
  18867. }
  18868. }
  18869. else if (!skipBody)
  18870. {
  18871. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  18872. bool wantsRetVal = true;
  18873. if ((mIsComptimeModule) && (methodDef->mMethodType != BfMethodType_CtorCalcAppend))
  18874. wantsRetVal = false;
  18875. else if (mCurMethodInstance->mReturnType->IsVar())
  18876. wantsRetVal = false;
  18877. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  18878. {
  18879. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  18880. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  18881. {
  18882. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  18883. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  18884. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst, mCurMethodInstance->mReturnType->mAlign);
  18885. mBfIRBuilder->ClearDebugLocation(storeInst);
  18886. mCurMethodState->mRetValAddr = allocaInst;
  18887. }
  18888. else if (wantsRetVal)
  18889. {
  18890. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  18891. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  18892. }
  18893. }
  18894. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  18895. {
  18896. mBfIRBuilder->CreateAlignedStore(GetConstValue(0), mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  18897. BfGetSymbolReferenceKind prevSymbolKind;
  18898. BfAutoComplete* prevAutoComplete;
  18899. if (mCompiler->mResolvePassData != NULL)
  18900. {
  18901. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  18902. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  18903. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  18904. }
  18905. EmitCtorCalcAppend();
  18906. if (mCompiler->mResolvePassData != NULL)
  18907. {
  18908. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  18909. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  18910. }
  18911. }
  18912. else if (!isEmptyBodied)
  18913. {
  18914. if (!mCurMethodState->mIRExitBlock)
  18915. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  18916. bool isExpressionBody = false;
  18917. if (methodDeclaration != NULL)
  18918. {
  18919. if (methodDeclaration->mFatArrowToken != NULL)
  18920. isExpressionBody = true;
  18921. }
  18922. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  18923. {
  18924. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  18925. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  18926. isExpressionBody = true;
  18927. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  18928. {
  18929. isExpressionBody = true;
  18930. }
  18931. }
  18932. else
  18933. {
  18934. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  18935. {
  18936. if (!block->mChildArr.IsEmpty())
  18937. {
  18938. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  18939. {
  18940. if (exprStmt->mTrailingSemicolon == NULL)
  18941. isExpressionBody = true;
  18942. }
  18943. }
  18944. }
  18945. else
  18946. isExpressionBody = true;
  18947. }
  18948. DoCEEmit(methodInstance);
  18949. if (methodInstance->mCeCancelled)
  18950. mIgnoreErrors = true;
  18951. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  18952. {
  18953. while (fieldDtorBody != NULL)
  18954. {
  18955. VisitEmbeddedStatement(fieldDtorBody->mBody);
  18956. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  18957. }
  18958. }
  18959. else if (!isExpressionBody)
  18960. {
  18961. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  18962. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  18963. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  18964. VisitCodeBlock(bodyBlock);
  18965. }
  18966. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  18967. {
  18968. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  18969. // {
  18970. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  18971. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  18972. // }
  18973. auto expectingType = mCurMethodInstance->mReturnType;
  18974. // What was this error for?
  18975. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  18976. // {
  18977. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  18978. // }
  18979. BfEvalExprFlags exprEvalFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_IsExpressionBody);
  18980. if (expectingType->IsVoid())
  18981. {
  18982. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  18983. bool wasReturnGenericParam = false;
  18984. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  18985. {
  18986. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  18987. }
  18988. else
  18989. {
  18990. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  18991. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  18992. wasReturnGenericParam = true;
  18993. }
  18994. // If we the void return was from a generic specialization, allow us to return a void result,
  18995. // otherwise treat expression as though it must be a statement
  18996. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  18997. if (isStatement)
  18998. expectingType = NULL;
  18999. }
  19000. BfExprEvaluator exprEvaluator(this);
  19001. if (mCurMethodInstance->mMethodDef->mIsReadOnly)
  19002. exprEvaluator.mAllowReadOnlyReference = true;
  19003. UpdateSrcPos(expressionBody);
  19004. auto retVal = CreateValueFromExpression(exprEvaluator, expressionBody, expectingType, exprEvalFlags);
  19005. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  19006. {
  19007. mCurMethodState->mHadReturn = true;
  19008. retVal = LoadOrAggregateValue(retVal);
  19009. EmitReturn(retVal);
  19010. }
  19011. }
  19012. }
  19013. }
  19014. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  19015. if (skipUpdateSrcPos)
  19016. {
  19017. // Skip
  19018. }
  19019. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19020. UpdateSrcPos(bodyBlock->mCloseBrace);
  19021. else if (methodDef->mBody != NULL)
  19022. UpdateSrcPos(methodDef->mBody);
  19023. else if (methodDeclaration != NULL)
  19024. UpdateSrcPos(methodDeclaration);
  19025. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  19026. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  19027. else
  19028. UseDefaultSrcPos();
  19029. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19030. {
  19031. if (mCurMethodState->mRetVal)
  19032. {
  19033. mCurMethodState->SetHadReturn(true);
  19034. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  19035. mBfIRBuilder->CreateRet(retVal);
  19036. }
  19037. else
  19038. AssertErrorState();
  19039. }
  19040. mCurMethodState->mHeadScope.mDone = true;
  19041. if (!mCurMethodState->mHadReturn)
  19042. {
  19043. // Clear off the stackallocs that have occurred after a scopeData break
  19044. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  19045. }
  19046. EmitDeferredCallProcessorInstances(&mCurMethodState->mHeadScope);
  19047. if (mCurMethodState->mIRExitBlock)
  19048. {
  19049. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  19050. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  19051. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  19052. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  19053. if ((!mCurMethodState->mDIRetVal) && (wantsDIData))
  19054. CreateDIRetVal();
  19055. }
  19056. for (auto localVar : mCurMethodState->mLocals)
  19057. {
  19058. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  19059. {
  19060. //
  19061. }
  19062. else if ((skipEndChecks) || (methodDef->mBody == NULL))
  19063. break;
  19064. LocalVariableDone(localVar, true);
  19065. }
  19066. if (mCurMethodState->mIRExitBlock)
  19067. {
  19068. if ((mCurMethodState->mRetVal) &&
  19069. ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() == -1)))
  19070. {
  19071. auto loadedVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19072. CreateReturn(loadedVal);
  19073. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19074. if (mCurMethodState->mDIRetVal)
  19075. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19076. }
  19077. else
  19078. {
  19079. // Have something on the last line to step onto
  19080. if (mHasFullDebugInfo)
  19081. {
  19082. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19083. UpdateSrcPos(bodyBlock->mCloseBrace);
  19084. EmitEnsureInstructionAt();
  19085. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19086. {
  19087. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19088. mBfIRBuilder->EnsureFunctionPatchable();
  19089. }
  19090. }
  19091. mBfIRBuilder->CreateRetVoid();
  19092. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19093. if (mCurMethodState->mDIRetVal)
  19094. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19095. }
  19096. }
  19097. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  19098. {
  19099. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  19100. {
  19101. if ((!mIsComptimeModule) && (irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19102. {
  19103. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19104. mBfIRBuilder->EnsureFunctionPatchable();
  19105. }
  19106. mBfIRBuilder->CreateRetVoid();
  19107. }
  19108. }
  19109. else
  19110. {
  19111. if (!mCurMethodState->mHadReturn)
  19112. {
  19113. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  19114. if (bodyBlock != NULL)
  19115. {
  19116. if (bodyBlock->mCloseBrace != NULL)
  19117. {
  19118. BfAstNode* target = bodyBlock->mCloseBrace;
  19119. if (!mCompiler->mHasRequiredTypes)
  19120. {
  19121. AddFailType(mCurTypeInstance);
  19122. mHadBuildError = true;
  19123. }
  19124. else
  19125. Fail("Method must return value", target);
  19126. }
  19127. else
  19128. {
  19129. // It's possible to not have a closing brace if the method ends in an EOF
  19130. AssertErrorState();
  19131. }
  19132. }
  19133. }
  19134. }
  19135. // Move 'init' into 'entry'
  19136. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  19137. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  19138. if (((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType())) &&
  19139. (!mIsComptimeModule))
  19140. {
  19141. // Don't keep instructions for unspecialized types
  19142. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19143. }
  19144. // Avoid linking any internal funcs that were just supposed to be comptime-accessible
  19145. /*if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  19146. wantsRemoveBody = true;*/
  19147. if ((hasExternSpecifier) && (!skipBody))
  19148. {
  19149. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  19150. // incase it gets called later by some hot-loaded coded
  19151. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()) && (mCurTypeInstance != mContext->mBfObjectType))
  19152. {
  19153. if (!mCurMethodInstance->mMethodDef->mName.StartsWith("Comptime_"))
  19154. CreateFakeCallerMethod(mangledName);
  19155. }
  19156. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19157. }
  19158. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  19159. {
  19160. // We only need the DLL stub when we may be hot swapping
  19161. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19162. }
  19163. else if (wantsRemoveBody)
  19164. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19165. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  19166. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  19167. // unspecialized types
  19168. if (((mCurTypeInstance->IsUnspecializedType()) && (!mIsComptimeModule)) ||
  19169. (mCurTypeInstance->IsInterface()))
  19170. {
  19171. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  19172. methodInstance->mIRFunction = BfIRFunction();
  19173. }
  19174. CheckAddFailType();
  19175. if (mHadBuildError)
  19176. prevHadBuildError.CancelRestore();
  19177. if (mHadBuildWarning)
  19178. prevHadWarning.CancelRestore();
  19179. if (!methodDef->mIsLocalMethod)
  19180. ProcessMethod_ProcessDeferredLocals();
  19181. prevIgnoreWrites.Restore();
  19182. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  19183. if (methodState.mHotDataReferenceBuilder != NULL)
  19184. {
  19185. AddHotDataReferences(&hotDataReferenceBuilder);
  19186. }
  19187. else
  19188. {
  19189. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  19190. {
  19191. // Remove the hot method data
  19192. auto hotMethod = methodInstance->mHotMethod;
  19193. auto prevMethod = hotMethod->mPrevVersion;
  19194. if (prevMethod != NULL)
  19195. {
  19196. // If there's a prev method then pull its data into the main HotMethod.
  19197. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  19198. // over to the main HotMethod definition to keep the HotMethod address
  19199. // invariant
  19200. for (auto ref : hotMethod->mReferences)
  19201. ref->Deref();
  19202. hotMethod->mReferences.Clear();
  19203. BF_ASSERT(prevMethod->mRefCount == 1);
  19204. hotMethod->mReferences = prevMethod->mReferences;
  19205. if (hotMethod->mSrcTypeVersion != NULL)
  19206. hotMethod->mSrcTypeVersion->Deref();
  19207. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  19208. prevMethod->mSrcTypeVersion = NULL;
  19209. prevMethod->mReferences.Clear();
  19210. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  19211. prevMethod->mPrevVersion = NULL;
  19212. prevMethod->Deref();
  19213. }
  19214. hotMethod->Deref();
  19215. methodInstance->mHotMethod = NULL;
  19216. }
  19217. }
  19218. }
  19219. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  19220. {
  19221. String name;
  19222. bool found = false;
  19223. auto checkMethodState = mCurMethodState;
  19224. while (checkMethodState != NULL)
  19225. {
  19226. if (checkMethodState->mClosureState == NULL)
  19227. break;
  19228. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  19229. {
  19230. found = true;
  19231. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  19232. break;
  19233. }
  19234. checkMethodState = checkMethodState->mPrevMethodState;
  19235. }
  19236. if (!found)
  19237. name += mCurMethodInstance->mMethodDef->mName;
  19238. int prevSepPos = (int)name.LastIndexOf('$');
  19239. if (prevSepPos != -1)
  19240. {
  19241. name.RemoveToEnd(prevSepPos);
  19242. }
  19243. name += "@";
  19244. name += baseName;
  19245. HashContext hashCtx;
  19246. if (anchorNode != NULL)
  19247. {
  19248. hashCtx.Mixin(anchorNode->GetStartCharId());
  19249. }
  19250. //
  19251. {
  19252. auto checkMethodState = declMethodState;
  19253. auto checkMixinState = declMixinState;
  19254. while (checkMethodState != NULL)
  19255. {
  19256. if (checkMixinState != NULL)
  19257. {
  19258. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  19259. }
  19260. checkMethodState = checkMethodState->mPrevMethodState;
  19261. if (checkMethodState != NULL)
  19262. checkMixinState = checkMethodState->mMixinState;
  19263. }
  19264. }
  19265. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19266. if ((rootMethodState != NULL) && (rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19267. {
  19268. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  19269. {
  19270. StringT<512> genericTypeName;
  19271. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  19272. hashCtx.MixinStr(genericTypeName);
  19273. }
  19274. }
  19275. uint64 hashVal = hashCtx.Finish64();
  19276. name += "$";
  19277. name += BfTypeUtils::HashEncode64(hashVal);
  19278. return name;
  19279. }
  19280. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  19281. {
  19282. if (localMethod->mMethodDef != NULL)
  19283. return localMethod->mMethodDef;
  19284. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19285. auto declMethodState = localMethod->mDeclMethodState;
  19286. auto declMixinState = localMethod->mDeclMixinState;
  19287. auto typeInst = mCurTypeInstance;
  19288. BfAstNode* body = NULL;
  19289. BfAstNode* anchorNode = NULL;
  19290. auto _AllocDirectTypeRef = [&](BfType* type)
  19291. {
  19292. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  19293. directTypeRef->Init(type);
  19294. return directTypeRef;
  19295. };
  19296. auto methodDeclaration = localMethod->mMethodDeclaration;
  19297. if (methodDeclaration != NULL)
  19298. {
  19299. body = methodDeclaration->mBody;
  19300. anchorNode = methodDeclaration->mOpenParen;
  19301. }
  19302. else
  19303. {
  19304. body = localMethod->mLambdaBindExpr->mBody;
  19305. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  19306. }
  19307. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  19308. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  19309. BfMethodDef* methodDef;
  19310. BfMethodDef* outerMethodDef = NULL;
  19311. if (localMethod->mOuterLocalMethod != NULL)
  19312. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  19313. else if (rootMethodState->mMethodInstance != NULL)
  19314. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  19315. if (methodDeclaration != NULL)
  19316. {
  19317. BfDefBuilder defBuilder(mCompiler->mSystem);
  19318. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  19319. defBuilder.mPassInstance = mCompiler->mPassInstance;
  19320. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  19321. defBuilder.mCurDeclaringTypeDef = defBuilder.mCurTypeDef;
  19322. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  19323. }
  19324. else
  19325. {
  19326. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  19327. methodDef = new BfMethodDef();
  19328. methodDef->mName = localMethod->mMethodName;
  19329. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  19330. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  19331. methodDef->mBody = body;
  19332. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  19333. {
  19334. auto paramType = invokeMethod->GetParamType(paramIdx);
  19335. String paramName;
  19336. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  19337. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  19338. else
  19339. paramName = invokeMethod->GetParamName(paramIdx);
  19340. auto paramDef = new BfParameterDef();
  19341. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  19342. paramDef->mName = paramName;
  19343. methodDef->mParams.Add(paramDef);
  19344. }
  19345. if (outerMethodDef != NULL)
  19346. {
  19347. for (auto genericParam : outerMethodDef->mGenericParams)
  19348. {
  19349. auto* copiedGenericParamDef = new BfGenericParamDef();
  19350. *copiedGenericParamDef = *genericParam;
  19351. methodDef->mGenericParams.Add(copiedGenericParamDef);
  19352. }
  19353. }
  19354. }
  19355. methodDef->mIdx = ~methodLocalIdx;
  19356. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  19357. methodDef->mName = localMethod->mExpectedFullName;
  19358. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  19359. //
  19360. // if (!localMethod->mExpectedFullName.IsEmpty())
  19361. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  19362. methodDef->mIsStatic = true;
  19363. methodDef->mIsLocalMethod = true;
  19364. methodDef->mIsVirtual = false;
  19365. localMethod->mMethodDef = methodDef;
  19366. auto methodInstanceGroup = new BfMethodInstanceGroup();
  19367. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  19368. methodInstanceGroup->mMethodIdx = -1;
  19369. methodInstanceGroup->mOwner = mCurTypeInstance;
  19370. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  19371. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  19372. {
  19373. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  19374. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  19375. }
  19376. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  19377. {
  19378. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  19379. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19380. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  19381. {
  19382. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  19383. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  19384. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  19385. autoComplete->mDefType = typeInst->mTypeDef;
  19386. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  19387. autoComplete->mReplaceLocalId = methodLocalIdx;
  19388. }
  19389. }
  19390. return localMethod->mMethodDef;
  19391. }
  19392. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  19393. {
  19394. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  19395. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  19396. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19397. auto declMethodState = localMethod->mDeclMethodState;
  19398. auto declMixinState = localMethod->mDeclMixinState;
  19399. auto callerMethodState = mCurMethodState;
  19400. auto typeInst = mCurTypeInstance;
  19401. if (mCurMethodState->mMixinState != NULL)
  19402. {
  19403. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  19404. }
  19405. auto methodDef = GetLocalMethodDef(localMethod);
  19406. BfAstNode* body = NULL;
  19407. auto methodDeclaration = localMethod->mMethodDeclaration;
  19408. if (methodDeclaration != NULL)
  19409. {
  19410. body = methodDeclaration->mBody;
  19411. }
  19412. else
  19413. {
  19414. body = localMethod->mLambdaBindExpr->mBody;
  19415. }
  19416. bool hadConcreteInterfaceGenericArgument = false;
  19417. BfTypeVector sanitizedMethodGenericArguments;
  19418. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  19419. // version of this method for this pass through the outermost method
  19420. int dependentGenericStartIdx = 0;
  19421. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19422. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  19423. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  19424. if (methodGenericArguments.size() == 0)
  19425. {
  19426. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19427. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  19428. }
  19429. else
  19430. {
  19431. int genericArgIdx = 0;
  19432. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  19433. // {
  19434. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  19435. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  19436. // }
  19437. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  19438. {
  19439. auto genericArgType = methodGenericArguments[genericArgIdx];
  19440. BF_ASSERT(!genericArgType->IsRef());
  19441. if (genericArgType->IsConcreteInterfaceType())
  19442. {
  19443. hadConcreteInterfaceGenericArgument = true;
  19444. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  19445. genericArgType = concreteInterfaceType->mInterface;
  19446. }
  19447. sanitizedMethodGenericArguments.push_back(genericArgType);
  19448. }
  19449. }
  19450. bool wantPrematureMethodInstance = false;
  19451. if (!force)
  19452. {
  19453. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  19454. }
  19455. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  19456. bool isDefaultPass = true;
  19457. BfTypeVector lookupMethodGenericArguments;
  19458. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  19459. {
  19460. auto genericArgType = methodGenericArguments[genericArgIdx];
  19461. BF_ASSERT(!genericArgType->IsRef());
  19462. lookupMethodGenericArguments.Add(genericArgType);
  19463. if (genericArgType->IsGenericParam())
  19464. {
  19465. auto genericParam = (BfGenericParamType*)genericArgType;
  19466. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  19467. isDefaultPass = false;
  19468. }
  19469. else
  19470. {
  19471. isDefaultPass = false;
  19472. }
  19473. }
  19474. bool hadExistingMethodInstance = false;
  19475. if (methodInstance != NULL)
  19476. {
  19477. hadExistingMethodInstance = true;
  19478. }
  19479. else
  19480. {
  19481. if (isDefaultPass)
  19482. {
  19483. methodInstance = methodInstGroup->mDefault;
  19484. if (methodInstance != NULL)
  19485. {
  19486. hadExistingMethodInstance = true;
  19487. }
  19488. else
  19489. {
  19490. methodInstance = new BfMethodInstance();
  19491. methodInstGroup->mDefault = methodInstance;
  19492. }
  19493. }
  19494. else
  19495. {
  19496. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  19497. if (methodInstGroup->mMethodSpecializationMap == NULL)
  19498. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  19499. BfMethodInstance** methodInstancePtr = NULL;
  19500. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  19501. {
  19502. methodInstance = *methodInstancePtr;
  19503. hadExistingMethodInstance = true;
  19504. }
  19505. else
  19506. {
  19507. methodInstance = new BfMethodInstance();
  19508. *methodInstancePtr = methodInstance;
  19509. }
  19510. }
  19511. }
  19512. if (hadExistingMethodInstance)
  19513. {
  19514. if ((!methodInstance->mDisallowCalling) ||
  19515. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  19516. return BfModuleMethodInstance(methodInstance);
  19517. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  19518. }
  19519. else
  19520. {
  19521. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  19522. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  19523. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  19524. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  19525. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  19526. methodInstance->mMethodDef = methodDef;
  19527. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  19528. if (hadConcreteInterfaceGenericArgument)
  19529. methodInstance->mIgnoreBody = true;
  19530. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  19531. for (auto genericArg : sanitizedMethodGenericArguments)
  19532. {
  19533. if (genericArg->IsPrimitiveType())
  19534. genericArg = GetWrappedStructType(genericArg);
  19535. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  19536. }
  19537. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  19538. {
  19539. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  19540. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  19541. }
  19542. SetupMethodIdHash(methodInstance);
  19543. }
  19544. auto _SetupMethodInstance = [&]()
  19545. {
  19546. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  19547. // Generic constraints
  19548. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  19549. {
  19550. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  19551. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  19552. }
  19553. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  19554. {
  19555. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  19556. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  19557. }
  19558. };
  19559. //////////////////////////////////////////////////////////////////////////
  19560. auto _VisitLambdaBody = [&]()
  19561. {
  19562. if (localMethod->mDeclOnly)
  19563. return;
  19564. if (mCompiler->mCanceling)
  19565. return;
  19566. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  19567. {
  19568. VisitCodeBlock(blockBody);
  19569. }
  19570. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  19571. {
  19572. BfType* expectType = NULL;
  19573. if (!methodInstance->mReturnType->IsVoid())
  19574. expectType = methodInstance->mReturnType;
  19575. CreateValueFromExpression(bodyExpr, expectType, BfEvalExprFlags_AllowRefExpr);
  19576. }
  19577. };
  19578. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  19579. {
  19580. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  19581. auto result = ResolveTypeRef(typeRef);
  19582. if (result == NULL)
  19583. result = mContext->mBfObjectType;
  19584. return result;
  19585. };
  19586. BfTypeInstance* outerClosure = NULL;
  19587. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  19588. outerClosure = declMethodState->mClosureState->mClosureType;
  19589. BfMethodState methodState;
  19590. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  19591. BfIRFunctionType funcType;
  19592. auto voidType = GetPrimitiveType(BfTypeCode_None);
  19593. SizedArray<BfIRType, 0> paramTypes;
  19594. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  19595. mBfIRBuilder->SaveDebugLocation();
  19596. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  19597. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  19598. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  19599. BfDeferredLocalAssignData deferredLocalAssignData;
  19600. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  19601. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  19602. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  19603. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  19604. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  19605. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  19606. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  19607. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  19608. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  19609. methodState.mIRFunction = declMethodState->mIRFunction;
  19610. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  19611. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  19612. {
  19613. methodState.mCurScope->mAstBlock = blockBody;
  19614. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  19615. }
  19616. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  19617. BfClosureState closureState;
  19618. if (methodDef->mMethodType == BfMethodType_Mixin)
  19619. {
  19620. if (declMethodState != NULL)
  19621. {
  19622. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  19623. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  19624. else if (declMethodState->mMethodInstance != NULL)
  19625. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  19626. }
  19627. }
  19628. if (closureState.mReturnType == NULL)
  19629. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  19630. closureState.mCapturing = true;
  19631. closureState.mLocalMethod = localMethod;
  19632. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  19633. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  19634. methodState.mClosureState = &closureState;
  19635. closureState.mClosureType = outerClosure;
  19636. int outerLocalsCount = (int)methodState.mLocals.size();
  19637. if (!hadExistingMethodInstance)
  19638. {
  19639. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  19640. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  19641. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  19642. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  19643. auto declareModule = this;
  19644. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  19645. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  19646. BF_ASSERT(declareModule != NULL);
  19647. methodInstance->mDeclModule = declareModule;
  19648. _SetupMethodInstance();
  19649. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  19650. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  19651. }
  19652. if (wantPrematureMethodInstance)
  19653. {
  19654. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  19655. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  19656. // its true method instance
  19657. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  19658. //BF_ASSERT(moduleMethodInstance);
  19659. return BfModuleMethodInstance(methodInstance);
  19660. }
  19661. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  19662. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  19663. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  19664. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  19665. closureState.mClosureMethodDef = methodDef;
  19666. bool wantsVisitBody = true;
  19667. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  19668. wantsVisitBody = false;
  19669. if (methodInstance->IsOrInUnspecializedVariation())
  19670. wantsVisitBody = false;
  19671. bool allowCapture = (methodDeclaration == NULL) || (methodDeclaration->mStaticSpecifier == NULL);
  19672. if (wantsVisitBody)
  19673. {
  19674. BP_ZONE("VisitLambdaBody");
  19675. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  19676. // this capture stage for each of those times
  19677. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  19678. /*
  19679. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  19680. // that will not occur during the actual lambda method generation, for example: returning a value
  19681. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  19682. // our AST nodes will still be visited
  19683. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  19684. */
  19685. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  19686. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  19687. mBfIRBuilder->SaveDebugLocation();
  19688. closureState.mCaptureVisitingBody = true;
  19689. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  19690. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  19691. methodState.mMethodInstance = methodInstance;
  19692. NewScopeState();
  19693. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  19694. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  19695. {
  19696. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  19697. for (auto localDef : methodState.mLocals)
  19698. {
  19699. if (localDef->mResolvedType->IsVar())
  19700. continue;
  19701. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  19702. }
  19703. }
  19704. // Keep outs from being marked as assigned
  19705. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19706. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  19707. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  19708. auto prevDLA = rootMethodState->mDeferredLocalAssignData;
  19709. while ((prevDLA != NULL) && (prevDLA->mIsChained))
  19710. prevDLA = prevDLA->mChainedAssignData;
  19711. if (prevDLA != NULL)
  19712. {
  19713. deferredLocalAssignData.mAssignedLocals = prevDLA->mAssignedLocals;
  19714. deferredLocalAssignData.mLeftBlockUncond = prevDLA->mLeftBlockUncond;
  19715. }
  19716. SetAndRestoreValue<BfDeferredLocalAssignData*> sarDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  19717. if (!mIgnoreErrors)
  19718. localMethod->mDidBodyErrorPass = true;
  19719. _VisitLambdaBody();
  19720. RestoreScopeState();
  19721. closureState.mCaptureVisitingBody = false;
  19722. mBfIRBuilder->RestoreDebugLocation();
  19723. }
  19724. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  19725. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  19726. {
  19727. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  19728. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  19729. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  19730. }
  19731. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  19732. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  19733. closureState.mClosureMethodDef = NULL;
  19734. for (auto methodInstance : closureState.mLocalMethodRefs)
  19735. {
  19736. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  19737. }
  19738. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  19739. prevIgnoreWrites.Restore();
  19740. std::multiset<BfClosureCapturedEntry> capturedEntries;
  19741. //
  19742. {
  19743. auto varMethodState = declMethodState;
  19744. while (varMethodState != NULL)
  19745. {
  19746. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  19747. {
  19748. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  19749. methodDef->mIsStatic = false;
  19750. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  19751. methodDef->mIsMutating = true;
  19752. }
  19753. bool copyOuterCaptures = false;
  19754. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  19755. {
  19756. auto localVar = varMethodState->mLocals[localIdx];
  19757. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  19758. {
  19759. if (!allowCapture)
  19760. {
  19761. if ((!localVar->mIsStatic) && (!localVar->mConstValue))
  19762. continue;
  19763. }
  19764. if (localVar->mIsThis)
  19765. {
  19766. // We can only set mutating if our owning type is mutating
  19767. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  19768. {
  19769. if (typeInst->IsValueType())
  19770. {
  19771. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  19772. methodDef->mIsMutating = true;
  19773. }
  19774. }
  19775. methodDef->mIsStatic = false;
  19776. continue;
  19777. }
  19778. if ((localVar->mIsThis) && (outerClosure != NULL))
  19779. {
  19780. continue;
  19781. }
  19782. if ((localVar->mConstValue) || (localVar->mIsStatic) || (localVar->mResolvedType->IsValuelessType()))
  19783. {
  19784. closureState.mConstLocals.push_back(*localVar);
  19785. continue;
  19786. }
  19787. BfClosureCapturedEntry capturedEntry;
  19788. auto capturedType = localVar->mResolvedType;
  19789. bool captureByRef = false;
  19790. if (!capturedType->IsRef())
  19791. {
  19792. if (localVar->mIsThis)
  19793. {
  19794. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  19795. captureByRef = true;
  19796. }
  19797. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  19798. captureByRef = true;
  19799. }
  19800. else
  19801. {
  19802. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  19803. {
  19804. capturedType = ((BfRefType*)capturedType)->mElementType;
  19805. }
  19806. }
  19807. if (captureByRef)
  19808. {
  19809. //capturedEntry.mIsByReference = true;
  19810. capturedType = CreateRefType(capturedType);
  19811. }
  19812. else
  19813. {
  19814. //capturedEntry.mIsByReference = false;
  19815. }
  19816. capturedEntry.mNameNode = localVar->mNameNode;
  19817. capturedEntry.mType = capturedType;
  19818. capturedEntry.mName = localVar->mName;
  19819. //capturedEntry.mLocalVarDef = localVar;
  19820. capturedEntries.insert(capturedEntry);
  19821. }
  19822. }
  19823. varMethodState = varMethodState->mPrevMethodState;
  19824. if ((varMethodState == NULL) ||
  19825. (varMethodState->mMixinState != NULL) ||
  19826. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  19827. break;
  19828. }
  19829. }
  19830. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  19831. {
  19832. auto fieldDef = copyField->GetFieldDef();
  19833. BfClosureCapturedEntry capturedEntry;
  19834. capturedEntry.mName = copyField->GetFieldDef()->mName;
  19835. capturedEntry.mType = copyField->mResolvedType;
  19836. if (capturedEntry.mType->IsRef())
  19837. {
  19838. // Keep by ref
  19839. }
  19840. else if (!fieldDef->mIsReadOnly)
  19841. {
  19842. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  19843. }
  19844. capturedEntries.insert(capturedEntry);
  19845. }
  19846. int captureIdx = 0;
  19847. for (auto& capturedEntry : capturedEntries)
  19848. {
  19849. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  19850. }
  19851. /*if (isDefaultPass)
  19852. {
  19853. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  19854. int captureIdx = 0;
  19855. for (auto& capturedEntry : capturedEntries)
  19856. {
  19857. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  19858. BfParameterDef* paramDef = new BfParameterDef();
  19859. paramDef->mName = capturedEntry.mName;
  19860. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  19861. directTypeRef->mType = capturedEntry.mType;
  19862. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  19863. paramDef->mTypeRef = directTypeRef;
  19864. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  19865. methodDef->mParams.Insert(captureIdx, paramDef);
  19866. captureIdx++;
  19867. }
  19868. }
  19869. else
  19870. {
  19871. auto defaultMethodInstance = methodInstGroup->mDefault;
  19872. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  19873. }*/
  19874. methodState.Reset();
  19875. closureState.mCapturing = false;
  19876. //////////////////////////////////////////////////////////////////////////
  19877. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  19878. if (methodInstance->mReturnType != NULL)
  19879. {
  19880. BF_ASSERT(methodInstance->mDisallowCalling);
  19881. // We did a premature declaration (without captures)
  19882. methodInstance->UndoDeclaration();
  19883. methodInstance->mDisallowCalling = false;
  19884. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  19885. }
  19886. auto declareModule = this;
  19887. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  19888. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  19889. BF_ASSERT(declareModule != NULL);
  19890. methodInstance->mDeclModule = declareModule;
  19891. _SetupMethodInstance();
  19892. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  19893. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  19894. closureState.mReturnType = methodInstance->mReturnType;
  19895. mCompiler->mStats.mMethodsQueued++;
  19896. mCompiler->UpdateCompletion();
  19897. declareModule->mIncompleteMethodCount++;
  19898. mCompiler->mStats.mMethodsProcessed++;
  19899. if (!methodInstance->mIsReified)
  19900. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  19901. auto deferMethodState = rootMethodState;
  19902. // Since we handle errors & warnings in the capture phase, we don't need to process any local methods for resolve-only (unless we're doing a mDbgVerifyCodeGen)
  19903. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  19904. (methodDef->mMethodType != BfMethodType_Mixin) &&
  19905. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)) &&
  19906. (!mCompiler->IsDataResolvePass()))
  19907. {
  19908. BP_ZONE("BfDeferredLocalMethod:create");
  19909. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  19910. deferredLocalMethod->mLocalMethod = localMethod;
  19911. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  19912. deferredLocalMethod->mMethodInstance = methodInstance;
  19913. auto checkMethodState = declMethodState;
  19914. while (checkMethodState != NULL)
  19915. {
  19916. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  19917. {
  19918. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  19919. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  19920. }
  19921. if (checkMethodState->mMixinState != NULL)
  19922. {
  19923. BfMixinRecord mixinRecord;
  19924. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  19925. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  19926. }
  19927. checkMethodState = checkMethodState->mPrevMethodState;
  19928. }
  19929. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  19930. }
  19931. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  19932. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  19933. mBfIRBuilder->RestoreDebugLocation();
  19934. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  19935. {
  19936. auto checkMethodState = mCurMethodState;
  19937. while (checkMethodState != NULL)
  19938. {
  19939. BfLocalMethod* nextLocalMethod = NULL;
  19940. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  19941. {
  19942. while (nextLocalMethod != NULL)
  19943. {
  19944. auto checkLocalMethod = nextLocalMethod;
  19945. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  19946. if (checkLocalMethod == localMethod)
  19947. continue;
  19948. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  19949. continue;
  19950. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  19951. if (checkMethodInstance == NULL)
  19952. continue; // Not generated yet
  19953. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  19954. {
  19955. String error = "Method already declared with the same parameter types";
  19956. auto bfError = Fail(error, methodInstance->mMethodDef->GetRefNode(), true);
  19957. if ((bfError != NULL) && (methodInstance->mMethodDef->GetRefNode() != checkMethodInstance->mMethodDef->GetRefNode()))
  19958. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  19959. }
  19960. }
  19961. }
  19962. checkMethodState = checkMethodState->mPrevMethodState;
  19963. }
  19964. }
  19965. return BfModuleMethodInstance(methodInstance);
  19966. }
  19967. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  19968. {
  19969. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  19970. return 0;
  19971. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19972. int rootMethodGenericParamCount = 0;
  19973. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  19974. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  19975. if (mCurMethodInstance == NULL)
  19976. return rootMethodGenericParamCount;
  19977. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  19978. return rootMethodGenericParamCount;
  19979. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  19980. if (callerLocalMethod == NULL)
  19981. return rootMethodGenericParamCount;
  19982. BfLocalMethod* calledLocalMethod = NULL;
  19983. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  19984. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  19985. {
  19986. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  19987. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  19988. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  19989. }
  19990. return rootMethodGenericParamCount;
  19991. }
  19992. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  19993. {
  19994. auto methodDef = methodInstance->mMethodDef;
  19995. auto customAttributes = methodInstance->GetCustomAttributes();
  19996. if (customAttributes != NULL)
  19997. return;
  19998. auto methodDeclaration = methodDef->GetMethodDeclaration();
  19999. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  20000. auto typeInstance = methodInstance->GetOwner();
  20001. if (typeInstance->IsInstanceOf(mCompiler->mValueTypeTypeDef))
  20002. return;
  20003. BfTypeState typeState(typeInstance);
  20004. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20005. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  20006. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20007. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  20008. BfAttributeDirective* attributeDirective = NULL;
  20009. if (methodDeclaration != NULL)
  20010. attributeDirective = methodDeclaration->mAttributes;
  20011. else if (propertyMethodDeclaration != NULL)
  20012. {
  20013. attributeDirective = propertyMethodDeclaration->mAttributes;
  20014. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  20015. {
  20016. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  20017. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  20018. }
  20019. }
  20020. if (attributeDirective != NULL)
  20021. {
  20022. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20023. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20024. if ((methodInstance == methodInstance->mMethodInstanceGroup->mDefault) && (methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes != NULL))
  20025. {
  20026. // Take over prevoiusly-generated custom attributes
  20027. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes;
  20028. methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes = NULL;
  20029. }
  20030. else
  20031. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  20032. }
  20033. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mPropertyDeclaration->mAttributes != NULL) && ((attrTarget & BfAttributeTargets_Property) == 0))
  20034. {
  20035. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes != NULL)
  20036. {
  20037. GetCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20038. }
  20039. else
  20040. {
  20041. methodInstance->GetMethodInfoEx()->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20042. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20043. }
  20044. }
  20045. customAttributes = methodInstance->GetCustomAttributes();
  20046. if (customAttributes == NULL)
  20047. {
  20048. auto owner = methodInstance->GetOwner();
  20049. if ((owner->IsDelegate()) || (owner->IsFunction()))
  20050. customAttributes = owner->mCustomAttributes;
  20051. }
  20052. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  20053. if (customAttributes != NULL)
  20054. {
  20055. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  20056. if (linkNameAttr != NULL)
  20057. {
  20058. if (linkNameAttr->mCtorArgs.size() == 1)
  20059. {
  20060. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  20061. if (constant != NULL)
  20062. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  20063. }
  20064. }
  20065. if (methodDef->mHasComptime)
  20066. methodInstance->mComptimeFlags = BfComptimeFlag_Comptime;
  20067. auto comptimeAttr = customAttributes->Get(mCompiler->mComptimeAttributeTypeDef);
  20068. if (comptimeAttr != NULL)
  20069. {
  20070. for (auto setProp : comptimeAttr->mSetProperties)
  20071. {
  20072. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  20073. if (propertyDef->mName == "OnlyFromComptime")
  20074. {
  20075. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  20076. if ((constant != NULL) && (constant->mBool))
  20077. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_OnlyFromComptime);
  20078. }
  20079. else if (propertyDef->mName == "ConstEval")
  20080. {
  20081. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  20082. if ((constant != NULL) && (constant->mBool))
  20083. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_ConstEval);
  20084. }
  20085. }
  20086. }
  20087. }
  20088. auto delegateInfo = typeInstance->GetDelegateInfo();
  20089. if ((delegateInfo != NULL) && (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) && (methodInstance->mMethodDef->mName == "Invoke"))
  20090. methodInstance->mCallingConvention = delegateInfo->mCallingConvention;
  20091. }
  20092. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  20093. {
  20094. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  20095. {
  20096. // Don't create a func
  20097. return;
  20098. }
  20099. auto typeInstance = methodInstance->GetOwner();
  20100. auto methodDef = methodInstance->mMethodDef;
  20101. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  20102. if (isTemporaryFunc)
  20103. {
  20104. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  20105. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  20106. mangledName = "autocomplete_tmp";
  20107. }
  20108. if (!mBfIRBuilder->mIgnoreWrites)
  20109. {
  20110. BfIRFunction prevFunc;
  20111. // Remove old version (if we have one)
  20112. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  20113. if (prevFunc)
  20114. {
  20115. if ((methodDef->mIsOverride) && (mCurTypeInstance->mTypeDef->mIsCombinedPartial))
  20116. {
  20117. bool takeover = false;
  20118. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  20119. BfMethodDef* nextMethod = NULL;
  20120. BfMemberSetEntry* entry = NULL;
  20121. if (mCurTypeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  20122. nextMethod = (BfMethodDef*)entry->mMemberDef;
  20123. while (nextMethod != NULL)
  20124. {
  20125. auto checkMethod = nextMethod;
  20126. nextMethod = nextMethod->mNextWithSameName;
  20127. if (checkMethod == methodDef)
  20128. continue;
  20129. if (checkMethod->mIsOverride)
  20130. {
  20131. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20132. if (checkMethodInstance == NULL)
  20133. continue;
  20134. if ((checkMethodInstance->mIRFunction == prevFunc) &&
  20135. (checkMethodInstance->mMethodDef->mMethodDeclaration != NULL) &&
  20136. (checkMethodInstance->mVirtualTableIdx < 0))
  20137. {
  20138. BfAstNode* refNode = methodDef->GetRefNode();
  20139. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  20140. refNode = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  20141. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  20142. refNode = methodDeclaration->mVirtualSpecifier;
  20143. auto error = Fail(StrFormat("Conflicting extension override method '%s'", MethodToString(mCurMethodInstance).c_str()), refNode);
  20144. if (error != NULL)
  20145. mCompiler->mPassInstance->MoreInfo("See previous override", checkMethod->GetRefNode());
  20146. takeover = false;
  20147. break;
  20148. }
  20149. }
  20150. if (!checkMethod->mIsExtern)
  20151. continue;
  20152. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20153. if (checkMethodInstance == NULL)
  20154. continue;
  20155. if (!CompareMethodSignatures(checkMethodInstance, mCurMethodInstance))
  20156. continue;
  20157. // Take over function
  20158. takeover = true;
  20159. }
  20160. if (takeover)
  20161. mCurMethodInstance->mIRFunction = prevFunc;
  20162. if (!mCurMethodInstance->mIRFunction)
  20163. {
  20164. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  20165. if (!mIsComptimeModule)
  20166. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  20167. }
  20168. }
  20169. else if (methodDef->mIsExtern)
  20170. {
  20171. // Allow this
  20172. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  20173. }
  20174. else if (typeInstance->IsIRFuncUsed(prevFunc))
  20175. {
  20176. // We can have a collision of names when we have generic methods that differ only in
  20177. // their constraints, but they should only collide in their unspecialized form
  20178. // since only one will be chosen for a given concrete type
  20179. if (!mIsComptimeModule)
  20180. mCurMethodInstance->mMangleWithIdx = true;
  20181. mangledName.Clear();
  20182. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  20183. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  20184. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  20185. }
  20186. else
  20187. {
  20188. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  20189. if (!mIsComptimeModule)
  20190. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  20191. }
  20192. }
  20193. }
  20194. if (typeInstance != mContext->mBfObjectType)
  20195. {
  20196. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  20197. GetMethodCustomAttributes(methodInstance);
  20198. }
  20199. // if (prevFunc)
  20200. // {
  20201. // if (methodDef->mIsExtern)
  20202. // {
  20203. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  20204. // methodInstance->mIRFunction = prevFunc;
  20205. // }
  20206. // else
  20207. // {
  20208. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  20209. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  20210. // {
  20211. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  20212. // BfLogSysM("Ignoring function name collision\n");
  20213. // }
  20214. // else
  20215. // {
  20216. // if (methodDef->mMethodDeclaration == NULL)
  20217. // {
  20218. // AssertErrorState();
  20219. // }
  20220. // else
  20221. // {
  20222. // BF_ASSERT(mIsSpecialModule);
  20223. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  20224. // {
  20225. // // We shouldn't have name collisions on the first run!
  20226. // AssertErrorState();
  20227. // }
  20228. // }
  20229. // }
  20230. // BfLogSysM("Before erase\n");
  20231. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  20232. // }
  20233. // }
  20234. bool isIntrinsic = false;
  20235. if (!methodInstance->mIRFunction)
  20236. {
  20237. BfIRFunction func;
  20238. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType() || (mIsComptimeModule)) &&
  20239. (!methodDef->IsEmptyPartial())) && (funcType);
  20240. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  20241. {
  20242. if (!mIsReified)
  20243. wantsLLVMFunc = false;
  20244. }*/
  20245. if (wantsLLVMFunc)
  20246. {
  20247. func = GetIntrinsic(methodInstance, true);
  20248. if (func)
  20249. {
  20250. isIntrinsic = true;
  20251. }
  20252. else
  20253. {
  20254. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  20255. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  20256. if (methodInstance->mAlwaysInline)
  20257. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  20258. // if (prevFunc)
  20259. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  20260. }
  20261. methodInstance->mIRFunction = func;
  20262. //if (!ignoreWrites)
  20263. //BF_ASSERT(!func.IsFake());
  20264. }
  20265. }
  20266. if (outIsIntrinsic != NULL)
  20267. *outIsIntrinsic = isIntrinsic;
  20268. if (!isIntrinsic)
  20269. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  20270. }
  20271. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  20272. {
  20273. if (methodInstance->mHotMethod != NULL)
  20274. return;
  20275. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  20276. {
  20277. auto srcTypeInst = methodInstance->GetOwner();
  20278. if (srcTypeInst->mHotTypeData == NULL)
  20279. return;
  20280. StringT<128> mangledName = inMangledName;
  20281. if (mangledName.IsEmpty())
  20282. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  20283. // We always keep the current primary method at the same address
  20284. BfHotMethod* hotMethod;
  20285. BfHotMethod** hotMethodPtr;
  20286. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  20287. {
  20288. hotMethod = new BfHotMethod();
  20289. *hotMethodPtr = hotMethod;
  20290. hotMethod->mRefCount = 1;
  20291. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20292. #ifdef BF_DBG_HOTMETHOD_IDX
  20293. static int sMethodIdx = 0;
  20294. hotMethod->mMethodIdx = sMethodIdx++;
  20295. #endif
  20296. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20297. }
  20298. else
  20299. {
  20300. hotMethod = *hotMethodPtr;
  20301. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  20302. {
  20303. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  20304. auto prevHotMethod = *hotMethodPtr;
  20305. hotMethod = new BfHotMethod();
  20306. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20307. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  20308. hotDupMethod->mRefCount++;
  20309. prevHotMethod->mReferences.Add(hotDupMethod);
  20310. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  20311. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20312. }
  20313. else if (mCompiler->IsHotCompile())
  20314. {
  20315. // Link the previous version into the mPrevVersion
  20316. BfHotMethod* prevMethod = new BfHotMethod();
  20317. prevMethod->mRefCount = 1;
  20318. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  20319. hotMethod->mPrevVersion = prevMethod;
  20320. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  20321. hotMethod->mSrcTypeVersion = NULL;
  20322. prevMethod->mFlags = hotMethod->mFlags;
  20323. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  20324. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  20325. #ifdef BF_DBG_HOTMETHOD_NAME
  20326. prevMethod->mMangledName = hotMethod->mMangledName;
  20327. #endif
  20328. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  20329. }
  20330. else
  20331. {
  20332. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20333. hotMethod->Clear(true);
  20334. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20335. }
  20336. }
  20337. if (methodInstance->mIsClosure)
  20338. {
  20339. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  20340. }
  20341. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  20342. hotMethod->mSrcTypeVersion->mRefCount++;
  20343. hotMethod->mRefCount++;
  20344. #ifdef BF_DBG_HOTMETHOD_NAME
  20345. hotMethod->mMangledName = mangledName;
  20346. #endif
  20347. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!IsHotCompile()))
  20348. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  20349. methodInstance->mHotMethod = hotMethod;
  20350. }
  20351. }
  20352. static void StackOverflow()
  20353. {
  20354. int i = 0;
  20355. if (i == 0)
  20356. StackOverflow();
  20357. }
  20358. void BfModule::StartMethodDeclaration(BfMethodInstance* methodInstance, BfMethodState* prevMethodState)
  20359. {
  20360. methodInstance->mHasStartedDeclaration = true;
  20361. auto methodDef = methodInstance->mMethodDef;
  20362. auto typeInstance = methodInstance->GetOwner();
  20363. bool hasNonGenericParams = false;
  20364. bool hasGenericParams = false;
  20365. int dependentGenericStartIdx = 0;
  20366. if (methodDef->mIsLocalMethod)
  20367. {
  20368. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  20369. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  20370. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  20371. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  20372. // over the local method each time
  20373. auto rootMethodInstance = prevMethodState->GetRootMethodState()->mMethodInstance;
  20374. dependentGenericStartIdx = 0;
  20375. if (rootMethodInstance != NULL)
  20376. {
  20377. if (rootMethodInstance->mMethodInfoEx != NULL)
  20378. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  20379. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  20380. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  20381. }
  20382. }
  20383. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodInstance->GetNumGenericArguments(); genericArgIdx++)
  20384. {
  20385. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  20386. if (genericArgType->IsGenericParam())
  20387. {
  20388. hasGenericParams = true;
  20389. auto genericParam = (BfGenericParamType*)genericArgType;
  20390. methodInstance->mIsUnspecialized = true;
  20391. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  20392. methodInstance->mIsUnspecializedVariation = true;
  20393. }
  20394. else
  20395. {
  20396. hasNonGenericParams = true;
  20397. if (genericArgType->IsUnspecializedType())
  20398. {
  20399. methodInstance->mIsUnspecialized = true;
  20400. methodInstance->mIsUnspecializedVariation = true;
  20401. }
  20402. }
  20403. }
  20404. if ((hasGenericParams) && (hasNonGenericParams))
  20405. {
  20406. methodInstance->mIsUnspecializedVariation = true;
  20407. }
  20408. if (typeInstance->IsUnspecializedType())
  20409. {
  20410. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  20411. // actually want to do method processing on it
  20412. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  20413. methodInstance->mIsUnspecializedVariation = true;
  20414. methodInstance->mIsUnspecialized = true;
  20415. }
  20416. if (methodInstance->mIsUnspecializedVariation)
  20417. BF_ASSERT(methodInstance->mIsUnspecialized);
  20418. //TODO: Why did we do this?
  20419. if (methodDef->mMethodType == BfMethodType_Mixin)
  20420. {
  20421. if (methodInstance->IsSpecializedGenericMethod())
  20422. methodInstance->mIsUnspecializedVariation = true;
  20423. methodInstance->mIsUnspecialized = true;
  20424. }
  20425. }
  20426. // methodDeclaration is NULL for default constructors
  20427. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  20428. {
  20429. BF_ASSERT((mCompiler->mCeMachine == NULL) || (!mCompiler->mCeMachine->mDbgPaused));
  20430. BP_ZONE("BfModule::DoMethodDeclaration");
  20431. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  20432. // to effectively make mIgnoreWrites method-scoped
  20433. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  20434. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  20435. SetAndRestoreValue<bool> prevAllowLockYield(mContext->mAllowLockYield, false);
  20436. BfTypeState typeState(mCurTypeInstance);
  20437. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20438. if (mCompiler->IsAutocomplete())
  20439. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  20440. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  20441. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  20442. BfMethodState methodState;
  20443. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  20444. methodState.mTempKind = BfMethodState::TempKind_Static;
  20445. defer({ mCurMethodInstance->mHasBeenDeclared = true; });
  20446. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  20447. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  20448. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  20449. // if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  20450. // {
  20451. // BF_ASSERT(mContext->mResolvingVarField);
  20452. // isTemporaryFunc = true;
  20453. // }
  20454. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  20455. FinishInit();
  20456. auto typeInstance = mCurTypeInstance;
  20457. auto typeDef = typeInstance->mTypeDef;
  20458. auto methodDef = mCurMethodInstance->mMethodDef;
  20459. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  20460. if (methodDef->mName == "__FATALERRORNAME")
  20461. BFMODULE_FATAL(this, "__FATALERRORNAME");
  20462. if (methodDef->mName == "__STACKOVERFLOW")
  20463. StackOverflow();
  20464. if (typeInstance->IsClosure())
  20465. {
  20466. if (methodDef->mName == "Invoke")
  20467. return;
  20468. }
  20469. auto methodInstance = mCurMethodInstance;
  20470. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  20471. addToWorkList = false;
  20472. if (!methodInstance->mHasStartedDeclaration)
  20473. StartMethodDeclaration(methodInstance, prevMethodState.mPrevVal);
  20474. BfAutoComplete* bfAutocomplete = NULL;
  20475. if (mCompiler->mResolvePassData != NULL)
  20476. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  20477. if (methodInstance->mMethodInfoEx != NULL)
  20478. {
  20479. BfTypeInstance* unspecializedTypeInstance = NULL;
  20480. Array<BfTypeReference*> deferredResolveTypes;
  20481. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  20482. {
  20483. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  20484. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  20485. {
  20486. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  20487. }
  20488. else
  20489. {
  20490. auto externConstraintDef = genericParam->GetExternConstraintDef();
  20491. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  20492. auto autoComplete = mCompiler->GetAutoComplete();
  20493. if (autoComplete != NULL)
  20494. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  20495. if (genericParam->mExternType != NULL)
  20496. {
  20497. //
  20498. }
  20499. else
  20500. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  20501. }
  20502. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized, &deferredResolveTypes);
  20503. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  20504. {
  20505. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  20506. if (bfAutocomplete != NULL)
  20507. {
  20508. for (auto nameNode : genericParamDef->mNameNodes)
  20509. {
  20510. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  20511. }
  20512. }
  20513. }
  20514. }
  20515. for (auto typeRef : deferredResolveTypes)
  20516. auto constraintType = ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_None);
  20517. if (methodInstance->mMethodInfoEx != NULL)
  20518. {
  20519. ValidateGenericParams(BfGenericParamKind_Method,
  20520. Span<BfGenericParamInstance*>((BfGenericParamInstance**)methodInstance->mMethodInfoEx->mGenericParams.mVals,
  20521. methodInstance->mMethodInfoEx->mGenericParams.mSize));
  20522. }
  20523. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  20524. AddDependency(genericParam, mCurTypeInstance);
  20525. }
  20526. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  20527. {
  20528. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  20529. BfAstNode* nameNode = methodDeclaration->mNameNode;
  20530. if (nameNode == NULL)
  20531. {
  20532. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  20533. nameNode = ctorDeclaration->mThisToken;
  20534. }
  20535. if ((autoComplete->IsAutocompleteNode(nameNode)) && (autoComplete->mResolveType != BfResolveType_Autocomplete))
  20536. {
  20537. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  20538. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  20539. autoComplete->mDefType = typeDef;
  20540. autoComplete->mDefMethod = methodDef;
  20541. autoComplete->SetDefinitionLocation(nameNode);
  20542. if (methodDef->mIsOverride)
  20543. {
  20544. bool found = false;
  20545. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  20546. {
  20547. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  20548. if (ventry.mDeclaringMethod.mMethodNum == -1)
  20549. continue;
  20550. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  20551. if (virtMethod != NULL)
  20552. {
  20553. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  20554. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  20555. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  20556. {
  20557. // Is matching method
  20558. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  20559. {
  20560. auto baseType = typeInstance->mBaseType;
  20561. if (baseType != NULL)
  20562. {
  20563. found = true;
  20564. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  20565. baseType = baseType->mBaseType;
  20566. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  20567. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  20568. autoComplete->mDefType = baseType->mTypeDef;
  20569. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  20570. }
  20571. }
  20572. break;
  20573. }
  20574. }
  20575. }
  20576. if ((!found) && (autoComplete->mIsGetDefinition) && (methodDef->mDeclaringType->IsExtension()))
  20577. {
  20578. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  20579. {
  20580. auto defaultMethod = methodGroup.mDefault;
  20581. if (defaultMethod == NULL)
  20582. continue;
  20583. if (!defaultMethod->mMethodDef->mIsExtern)
  20584. continue;
  20585. if (!CompareMethodSignatures(defaultMethod, methodInstance))
  20586. continue;
  20587. autoComplete->SetDefinitionLocation(defaultMethod->mMethodDef->GetRefNode(), true);
  20588. autoComplete->mDefType = typeInstance->mTypeDef;
  20589. autoComplete->mDefMethod = defaultMethod->mMethodDef;
  20590. }
  20591. }
  20592. }
  20593. }
  20594. }
  20595. bool reportErrors = true;
  20596. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  20597. reportErrors = true;
  20598. // Only the defining contexts needs to report errors here
  20599. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  20600. if (methodDef->mMethodType == BfMethodType_Dtor)
  20601. {
  20602. if (methodDef->mIsStatic)
  20603. {
  20604. }
  20605. else
  20606. {
  20607. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  20608. {
  20609. BfAstNode* refNode = methodDeclaration;
  20610. if (refNode == NULL)
  20611. {
  20612. // Whatever caused this ctor to be generated should have caused another failure
  20613. // But that failure might not be generated until the ctor is generated
  20614. }
  20615. else
  20616. {
  20617. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  20618. if (dtorDecl != NULL)
  20619. refNode = dtorDecl->mThisToken;
  20620. Fail("Structs cannot have destructors", refNode);
  20621. }
  20622. }
  20623. auto methodDeclaration = methodDef->GetMethodDeclaration();
  20624. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  20625. (mCurTypeInstance != mContext->mBfObjectType))
  20626. {
  20627. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  20628. }
  20629. }
  20630. }
  20631. BfType* resolvedReturnType = NULL;
  20632. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  20633. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  20634. (methodDef->mReturnTypeRef != NULL))
  20635. {
  20636. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  20637. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric);
  20638. if ((((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0) || (methodInstance->mIsAutocompleteMethod))
  20639. && (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>()))
  20640. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  20641. else
  20642. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration, flags);
  20643. if (resolvedReturnType == NULL)
  20644. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  20645. if ((methodDef->mIsReadOnly) && (!resolvedReturnType->IsRef()))
  20646. {
  20647. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration))
  20648. if (methodDeclaration->mReadOnlySpecifier != NULL)
  20649. Fail("Readonly specifier is only valid on 'ref' return types", methodDeclaration->mReadOnlySpecifier);
  20650. }
  20651. }
  20652. else
  20653. {
  20654. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  20655. }
  20656. BF_ASSERT(resolvedReturnType != NULL);
  20657. mCurMethodInstance->mReturnType = resolvedReturnType;
  20658. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  20659. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  20660. //if (!methodInstance->IsSpecializedGenericMethod())
  20661. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  20662. if (methodDef->mExplicitInterface != NULL)
  20663. {
  20664. auto autoComplete = mCompiler->GetAutoComplete();
  20665. if (autoComplete != NULL)
  20666. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  20667. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  20668. BfTypeInstance* explicitInterface = NULL;
  20669. if (explicitType != NULL)
  20670. explicitInterface = explicitType->ToTypeInstance();
  20671. if (explicitInterface != NULL)
  20672. {
  20673. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  20674. if (autoComplete != NULL)
  20675. {
  20676. BfTokenNode* dotToken = NULL;
  20677. BfAstNode* nameNode = NULL;
  20678. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  20679. {
  20680. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  20681. nameNode = methodDeclaration->mNameNode;
  20682. }
  20683. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  20684. }
  20685. }
  20686. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  20687. {
  20688. bool interfaceFound = false;
  20689. for (auto ifaceInst : typeInstance->mInterfaces)
  20690. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  20691. if ((!interfaceFound) && (!typeInstance->mTypeFailed))
  20692. {
  20693. if (methodDef->mMethodDeclaration != NULL)
  20694. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  20695. else
  20696. {
  20697. // For property decls, we should have already given the error during type population
  20698. if (mCompiler->mRevision == 1)
  20699. AssertErrorState();
  20700. }
  20701. }
  20702. }
  20703. }
  20704. bool isThisStruct = mCurTypeInstance->IsStruct();
  20705. BfType* thisType = NULL;
  20706. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  20707. {
  20708. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  20709. {
  20710. thisType = mCurTypeInstance;
  20711. if (thisType == NULL)
  20712. return;
  20713. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  20714. {
  20715. BfTypeUtils::SplatIterate([&](BfType* checkType)
  20716. {
  20717. PopulateType(checkType, BfPopulateType_Data);
  20718. }, thisType);
  20719. }
  20720. }
  20721. else
  20722. {
  20723. thisType = mCurTypeInstance;
  20724. PopulateType(thisType, BfPopulateType_Declaration);
  20725. }
  20726. }
  20727. int implicitParamCount = 0;
  20728. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  20729. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  20730. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  20731. bool hadDelegateParams = false;
  20732. bool hadParams = false;
  20733. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  20734. {
  20735. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  20736. BfParameterDef* paramDef = NULL;
  20737. int paramDefIdx = -1;
  20738. if (paramIdx < implicitParamCount)
  20739. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  20740. else
  20741. {
  20742. paramDefIdx = paramIdx - implicitParamCount;
  20743. paramDef = methodDef->mParams[paramDefIdx];
  20744. }
  20745. if (hadParams)
  20746. break;
  20747. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  20748. continue;
  20749. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  20750. (paramDef->mParamKind != BfParamKind_AppendIdx))
  20751. {
  20752. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  20753. if (mCompiler->mResolvePassData->mAutoComplete->IsAutocompleteNode(paramDef->mTypeRef))
  20754. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("token", "in"), paramDef->mTypeRef->ToString());
  20755. }
  20756. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  20757. {
  20758. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20759. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20760. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  20761. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  20762. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  20763. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  20764. }
  20765. BfType* resolvedParamType = NULL;
  20766. if (closureCaptureEntry != NULL)
  20767. resolvedParamType = closureCaptureEntry->mType;
  20768. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfLetTypeReference>()))
  20769. {
  20770. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  20771. resolvedParamType = mContext->mBfObjectType;
  20772. }
  20773. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfVarTypeReference>()))
  20774. {
  20775. if (methodDef->mMethodType != BfMethodType_Mixin)
  20776. {
  20777. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  20778. resolvedParamType = mContext->mBfObjectType;
  20779. }
  20780. else
  20781. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  20782. }
  20783. BfType* unresolvedParamType = resolvedParamType;
  20784. bool wasGenericParam = false;
  20785. if (resolvedParamType == NULL)
  20786. {
  20787. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  20788. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  20789. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  20790. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  20791. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  20792. resolvedParamType = resolvedParamType->GetUnderlyingType();
  20793. }
  20794. if (resolvedParamType == NULL)
  20795. {
  20796. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  20797. unresolvedParamType = resolvedParamType;
  20798. if (mCurTypeInstance->IsBoxed())
  20799. {
  20800. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  20801. // If we failed a lookup here then we better have also failed it in the original type
  20802. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.ContainsKey(boxedType->mElementType->ToTypeInstance()));
  20803. }
  20804. }
  20805. BF_ASSERT(!resolvedParamType->IsDeleting());
  20806. if (!methodInstance->IsSpecializedGenericMethod())
  20807. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  20808. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  20809. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  20810. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  20811. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  20812. {
  20813. if (paramDef->mParamKind == BfParamKind_Params)
  20814. {
  20815. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  20816. if (refNode != NULL)
  20817. refNode = paramDef->mParamDeclaration->mModToken;
  20818. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  20819. }
  20820. BfTypedValue defaultValue;
  20821. if (resolvedParamType->IsConstExprValue())
  20822. {
  20823. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  20824. BfExprEvaluator exprEvaluator(this);
  20825. exprEvaluator.mExpectingType = constExprType->mType;
  20826. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  20827. defaultValue = exprEvaluator.GetResult();
  20828. }
  20829. else
  20830. {
  20831. BfTypeState typeState;
  20832. typeState.mType = mCurTypeInstance;
  20833. typeState.mCurTypeDef = methodDef->mDeclaringType;
  20834. //typeState.mCurMethodDef = methodDef;
  20835. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20836. BfConstResolver constResolver(this);
  20837. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  20838. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  20839. {
  20840. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  20841. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  20842. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  20843. {
  20844. defaultValue = castedDefaultValue; // Good!
  20845. }
  20846. else if (!CanCast(defaultValue, resolvedParamType))
  20847. {
  20848. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  20849. // a conversion operator.
  20850. // This should throw an error
  20851. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  20852. AssertErrorState();
  20853. if (!defaultValue.mValue.IsConst())
  20854. defaultValue = BfTypedValue();
  20855. }
  20856. }
  20857. }
  20858. if (!defaultValue)
  20859. {
  20860. defaultValue = GetDefaultTypedValue(resolvedParamType);
  20861. if (!defaultValue.mValue.IsConst())
  20862. defaultValue = BfTypedValue();
  20863. }
  20864. if (defaultValue)
  20865. {
  20866. if (defaultValue.mType->IsVar())
  20867. {
  20868. AssertErrorState();
  20869. }
  20870. else
  20871. {
  20872. BF_ASSERT(defaultValue.mValue.IsConst());
  20873. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  20874. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  20875. CurrentAddToConstHolder(defaultValue.mValue);
  20876. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  20877. }
  20878. }
  20879. }
  20880. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  20881. {
  20882. bool addParams = true;
  20883. bool isValid = false;
  20884. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  20885. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->IsInstanceOf(mCompiler->mSpanTypeDef)))
  20886. {
  20887. // Span<T>
  20888. isValid = true;
  20889. }
  20890. else if (resolvedParamType->IsArray())
  20891. {
  20892. // Array is the 'normal' params type
  20893. isValid = true;
  20894. }
  20895. else if (resolvedParamType->IsSizedArray())
  20896. {
  20897. isValid = true;
  20898. }
  20899. else if (resolvedParamType->IsVar())
  20900. {
  20901. isValid = true;
  20902. }
  20903. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()) || (resolvedParamType->IsMethodRef()))
  20904. {
  20905. hadDelegateParams = true;
  20906. // This means we copy the params from a delegate
  20907. BfMethodParam methodParam;
  20908. methodParam.mResolvedType = resolvedParamType;
  20909. methodParam.mParamDefIdx = paramDefIdx;
  20910. methodParam.mDelegateParamIdx = 0;
  20911. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  20912. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  20913. {
  20914. methodParam.mDelegateParamIdx = delegateParamIdx;
  20915. mCurMethodInstance->mParams.Add(methodParam);
  20916. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  20917. if (!methodInstance->IsSpecializedGenericMethod())
  20918. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  20919. }
  20920. isValid = true;
  20921. addParams = false;
  20922. }
  20923. else if (resolvedParamType->IsGenericParam())
  20924. {
  20925. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  20926. if (genericParamInstance->mTypeConstraint != NULL)
  20927. {
  20928. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  20929. if ((genericParamInstance->mTypeConstraint->IsArray()) || (genericParamInstance->mTypeConstraint->IsSizedArray()))
  20930. {
  20931. BfMethodParam methodParam;
  20932. methodParam.mResolvedType = resolvedParamType;
  20933. methodParam.mParamDefIdx = paramDefIdx;
  20934. mCurMethodInstance->mParams.Add(methodParam);
  20935. isValid = true;
  20936. }
  20937. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  20938. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  20939. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  20940. {
  20941. mCurMethodInstance->mHadGenericDelegateParams = true;
  20942. isValid = true;
  20943. addParams = false;
  20944. }
  20945. }
  20946. }
  20947. else
  20948. {
  20949. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  20950. if ((paramTypeInst != NULL) &&
  20951. ((paramTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef))))
  20952. {
  20953. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  20954. isValid = true;
  20955. addParams = false;
  20956. }
  20957. }
  20958. if (!isValid)
  20959. {
  20960. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  20961. // Failure case, make it an Object[]
  20962. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  20963. }
  20964. if ((addParams) && (resolvedParamType != NULL))
  20965. {
  20966. BfMethodParam methodParam;
  20967. methodParam.mResolvedType = resolvedParamType;
  20968. methodParam.mParamDefIdx = paramDefIdx;
  20969. mCurMethodInstance->mParams.push_back(methodParam);
  20970. }
  20971. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  20972. {
  20973. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  20974. }
  20975. }
  20976. else
  20977. {
  20978. BfMethodParam methodParam;
  20979. methodParam.mResolvedType = resolvedParamType;
  20980. methodParam.mParamDefIdx = paramDefIdx;
  20981. mCurMethodInstance->mParams.Add(methodParam);
  20982. }
  20983. }
  20984. if (hadDelegateParams)
  20985. {
  20986. HashSet<String> usedNames;
  20987. Dictionary<int, int> usedParamDefIdx;
  20988. for (auto methodParam : methodDef->mParams)
  20989. {
  20990. usedNames.Add(methodParam->mName);
  20991. }
  20992. for (auto& methodParam : mCurMethodInstance->mParams)
  20993. {
  20994. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  20995. {
  20996. int* refCount = NULL;
  20997. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  20998. (*refCount)++;
  20999. }
  21000. }
  21001. for (auto& methodParam : mCurMethodInstance->mParams)
  21002. {
  21003. if (methodParam.mDelegateParamIdx != -1)
  21004. {
  21005. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  21006. methodParam.mDelegateParamNameCombine = true;
  21007. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21008. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  21009. if (usedNames.Contains(paramName))
  21010. methodParam.mDelegateParamNameCombine = true;
  21011. }
  21012. }
  21013. }
  21014. int argIdx = 0;
  21015. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  21016. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  21017. {
  21018. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  21019. auto thisType = methodInstance->GetOwner();
  21020. if (methodInstance->GetParamIsSplat(thisIdx))
  21021. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  21022. else if (!thisType->IsValuelessType())
  21023. {
  21024. BfTypeCode loweredTypeCode = BfTypeCode_None;
  21025. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  21026. if ((!mIsComptimeModule) && (!methodDef->mIsMutating))
  21027. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  21028. argIdx++;
  21029. if (loweredTypeCode2 != BfTypeCode_None)
  21030. argIdx++;
  21031. }
  21032. }
  21033. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  21034. argIdx++;
  21035. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  21036. {
  21037. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  21038. BfType* checkType = methodParam.mResolvedType;
  21039. int checkArgIdx = argIdx;
  21040. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  21041. {
  21042. checkArgIdx = 0;
  21043. checkType = methodInstance->GetThisType();
  21044. }
  21045. if (checkType->IsMethodRef())
  21046. {
  21047. methodParam.mIsSplat = true;
  21048. }
  21049. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting(paramIdx)))
  21050. {
  21051. PopulateType(checkType, BfPopulateType_Data);
  21052. if (checkType->IsSplattable())
  21053. {
  21054. bool isSplat = false;
  21055. auto checkTypeInstance = checkType->ToTypeInstance();
  21056. if ((checkTypeInstance != NULL) && (checkTypeInstance->mIsCRepr))
  21057. isSplat = true;
  21058. int splatCount = checkType->GetSplatCount();
  21059. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  21060. isSplat = true;
  21061. if (isSplat)
  21062. {
  21063. methodParam.mIsSplat = true;
  21064. argIdx += splatCount;
  21065. continue;
  21066. }
  21067. }
  21068. else if (!checkType->IsValuelessType())
  21069. {
  21070. BfTypeCode loweredTypeCode = BfTypeCode_None;
  21071. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  21072. if (!mIsComptimeModule)
  21073. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  21074. argIdx++;
  21075. if (loweredTypeCode2 != BfTypeCode_None)
  21076. argIdx++;
  21077. continue;
  21078. }
  21079. }
  21080. argIdx++;
  21081. }
  21082. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  21083. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  21084. {
  21085. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  21086. }
  21087. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  21088. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  21089. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  21090. (!methodDef->mIsSkipCall))
  21091. {
  21092. if (methodDeclaration->mEndSemicolon == NULL)
  21093. {
  21094. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  21095. {
  21096. //
  21097. }
  21098. else
  21099. AssertParseErrorState();
  21100. }
  21101. else
  21102. {
  21103. bool isError = true;
  21104. if (typeInstance->IsTypedPrimitive())
  21105. {
  21106. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  21107. {
  21108. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  21109. {
  21110. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  21111. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  21112. {
  21113. isError = false;
  21114. }
  21115. }
  21116. }
  21117. }
  21118. if (isError)
  21119. {
  21120. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  21121. MethodToString(methodInstance).c_str()),
  21122. methodDef->GetRefNode());
  21123. }
  21124. }
  21125. }
  21126. if (methodDef->IsEmptyPartial())
  21127. hasExternSpecifier = true;
  21128. if (!methodInstance->IsAutocompleteMethod())
  21129. {
  21130. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  21131. int implicitParamCount = methodInstance->GetImplicitParamCount();
  21132. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  21133. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  21134. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  21135. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  21136. int paramIdx = 0;
  21137. int defaultParamIdx = 0;
  21138. while (true)
  21139. {
  21140. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  21141. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  21142. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  21143. {
  21144. paramIdx++;
  21145. continue;
  21146. }
  21147. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  21148. {
  21149. defaultParamIdx++;
  21150. continue;
  21151. }
  21152. if ((isDone) || (isDefaultDone))
  21153. {
  21154. // If we have generic delegate params, it's possible we will fail constraints later if we specialize with an invalid type, but we can't allow that
  21155. // to cause us to throw an assertion in the declaration here
  21156. if ((!defaultMethodInstance->mHadGenericDelegateParams) && (!methodInstance->mHasFailed) && (!defaultMethodInstance->mHasFailed))
  21157. BF_ASSERT((isDone) && (isDefaultDone));
  21158. break;
  21159. }
  21160. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  21161. if (paramType->IsRef())
  21162. paramType = paramType->GetUnderlyingType();
  21163. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  21164. paramIdx++;
  21165. defaultParamIdx++;
  21166. }
  21167. }
  21168. StringT<4096> mangledName;
  21169. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  21170. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  21171. {
  21172. auto paramType = methodInstance->GetParamType(paramIdx);
  21173. if (paramType->IsComposite())
  21174. PopulateType(paramType, BfPopulateType_Data);
  21175. if (!methodInstance->IsParamSkipped(paramIdx))
  21176. {
  21177. if (paramType->IsStruct())
  21178. {
  21179. //
  21180. }
  21181. else
  21182. {
  21183. PopulateType(paramType, BfPopulateType_Declaration);
  21184. }
  21185. }
  21186. }
  21187. // Only process method in default unspecialized mode, not in variations
  21188. if (methodInstance->mIsUnspecializedVariation)
  21189. return;
  21190. PopulateType(resolvedReturnType, BfPopulateType_Data);
  21191. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  21192. if (resolvedReturnType->IsValuelessType())
  21193. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  21194. if (!mBfIRBuilder->mIgnoreWrites)
  21195. {
  21196. bool isIntrinsic = false;
  21197. if (!methodInstance->mIRFunction)
  21198. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  21199. if (isIntrinsic)
  21200. {
  21201. addToWorkList = false;
  21202. }
  21203. }
  21204. else
  21205. {
  21206. GetMethodCustomAttributes(methodInstance);
  21207. }
  21208. auto func = methodInstance->mIRFunction;
  21209. // if (methodInstance->mIsReified)
  21210. // CheckHotMethod(methodInstance, mangledName);
  21211. for (auto& param : methodInstance->mParams)
  21212. {
  21213. BF_ASSERT(!param.mResolvedType->IsDeleting());
  21214. }
  21215. BfLogSysM("DoMethodDeclaration %s Module: %p Type: %p MethodInst: %p Reified: %d Unspecialized: %d IRFunction: %d MethodId:%llx\n", mangledName.c_str(), this, mCurTypeInstance, methodInstance, methodInstance->mIsReified, mCurTypeInstance->IsUnspecializedType(), methodInstance->mIRFunction.mId, methodInstance->mIdHash);
  21216. SizedArray<BfIRMDNode, 8> diParams;
  21217. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  21218. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  21219. {
  21220. //CS0708
  21221. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  21222. }
  21223. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  21224. {
  21225. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  21226. methodDef->mIsVirtual = false;
  21227. }
  21228. BfAstNode* mutSpecifier = NULL;
  21229. if (methodDeclaration != NULL)
  21230. mutSpecifier = methodDeclaration->mMutSpecifier;
  21231. else if (methodDef->GetPropertyMethodDeclaration() != NULL)
  21232. {
  21233. mutSpecifier = methodDef->GetPropertyMethodDeclaration()->mMutSpecifier;
  21234. if (mutSpecifier == NULL)
  21235. {
  21236. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21237. if (propertyDeclaration != NULL)
  21238. {
  21239. if (auto propExprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  21240. mutSpecifier = propExprBody->mMutSpecifier;
  21241. }
  21242. }
  21243. }
  21244. if ((mutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  21245. {
  21246. if (methodDef->mIsStatic)
  21247. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", mutSpecifier);
  21248. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  21249. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", mutSpecifier);
  21250. else if (methodDef->mMethodType == BfMethodType_Ctor)
  21251. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", mutSpecifier);
  21252. else if (methodDef->mMethodType == BfMethodType_Dtor)
  21253. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", mutSpecifier);
  21254. }
  21255. if (isTemporaryFunc)
  21256. {
  21257. // This handles temporary methods for autocomplete types
  21258. //BF_ASSERT(mIsScratchModule);
  21259. //BF_ASSERT(mCompiler->IsAutocomplete());
  21260. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  21261. return; // Bail out early for autocomplete pass
  21262. }
  21263. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  21264. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  21265. // autocompleter. Why did we have this check anyway?
  21266. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  21267. {
  21268. AddMethodReference(methodInstance);
  21269. mFuncReferences[methodInstance] = func;
  21270. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  21271. }*/
  21272. if (mParentModule != NULL)
  21273. {
  21274. // For extension modules we need to keep track of our own methods so we can know which methods
  21275. // we have defined ourselves and which are from the parent module or other extensions
  21276. if (!func.IsFake())
  21277. {
  21278. if (func)
  21279. mFuncReferences[methodInstance] = func;
  21280. }
  21281. }
  21282. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  21283. {
  21284. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  21285. auto owningModule = methodInstance->GetOwner()->mModule;
  21286. if (!owningModule->mIsScratchModule)
  21287. owningModule->mOnDemandMethodCount++;
  21288. VerifyOnDemandMethods();
  21289. }
  21290. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  21291. if (wasAwaitingDecl)
  21292. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  21293. if (addToWorkList)
  21294. {
  21295. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  21296. {
  21297. AddMethodToWorkList(methodInstance);
  21298. }
  21299. else
  21300. {
  21301. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  21302. methodInstance->mIgnoreBody = true;
  21303. if (typeInstance->IsUnspecializedType())
  21304. {
  21305. // Don't hold on to actual Function for unspecialized types
  21306. methodInstance->mIRFunction = BfIRFunction();
  21307. }
  21308. }
  21309. }
  21310. else
  21311. {
  21312. //BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  21313. }
  21314. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  21315. (!methodDef->mIsLocalMethod) &&
  21316. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  21317. (!methodDef->mReturnTypeRef->IsTemporary()))
  21318. {
  21319. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  21320. {
  21321. //TODO:
  21322. //CS0053
  21323. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  21324. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  21325. methodDef->mReturnTypeRef, true);
  21326. }
  21327. else
  21328. {
  21329. //CS0050
  21330. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  21331. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  21332. methodDef->mReturnTypeRef, true);
  21333. }
  21334. }
  21335. if (typeInstance->IsInterface())
  21336. {
  21337. if (methodDef->mMethodType == BfMethodType_Ctor)
  21338. Fail("Interfaces cannot contain constructors", methodDeclaration);
  21339. if (methodDeclaration != NULL)
  21340. {
  21341. if (methodDef->mBody == NULL)
  21342. {
  21343. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  21344. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  21345. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  21346. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  21347. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  21348. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  21349. }
  21350. }
  21351. }
  21352. bool foundHiddenMethod = false;
  21353. BfTokenNode* virtualToken = NULL;
  21354. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21355. if (propertyDeclaration != NULL)
  21356. virtualToken = propertyDeclaration->mVirtualSpecifier;
  21357. else if (methodDeclaration != NULL)
  21358. virtualToken = methodDeclaration->mVirtualSpecifier;
  21359. // Don't compare specialized generic methods against normal methods
  21360. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  21361. (!methodDef->mIsLocalMethod) && (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  21362. {
  21363. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  21364. {
  21365. typeDef->PopulateMemberSets();
  21366. BfMethodDef* nextMethod = NULL;
  21367. BfMemberSetEntry* entry = NULL;
  21368. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21369. nextMethod = (BfMethodDef*)entry->mMemberDef;
  21370. while (nextMethod != NULL)
  21371. {
  21372. auto checkMethod = nextMethod;
  21373. nextMethod = nextMethod->mNextWithSameName;
  21374. if (checkMethod == methodDef)
  21375. continue;
  21376. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21377. if (checkMethodInstance == NULL)
  21378. {
  21379. if ((methodDef->mDeclaringType->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension()))
  21380. checkMethodInstance = GetRawMethodInstanceAtIdx(typeInstance, checkMethod->mIdx);
  21381. if (checkMethodInstance == NULL)
  21382. continue;
  21383. }
  21384. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  21385. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  21386. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  21387. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  21388. {
  21389. bool canChain = false;
  21390. if ((methodDef->mParams.empty()) &&
  21391. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  21392. {
  21393. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  21394. canChain = true;
  21395. else if (methodDef->mMethodType == BfMethodType_Normal)
  21396. {
  21397. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  21398. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  21399. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  21400. canChain = true;
  21401. }
  21402. }
  21403. if (canChain)
  21404. {
  21405. bool isBetter;
  21406. bool isWorse;
  21407. CompareDeclTypes(typeInstance, checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  21408. if (isBetter && !isWorse)
  21409. {
  21410. methodInstance->mChainType = BfMethodChainType_ChainHead;
  21411. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  21412. }
  21413. else
  21414. {
  21415. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  21416. methodInstance->mChainType = BfMethodChainType_ChainMember;
  21417. }
  21418. }
  21419. else
  21420. {
  21421. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  21422. continue;
  21423. bool silentlyAllow = false;
  21424. bool extensionWarn = false;
  21425. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  21426. {
  21427. if (typeInstance->IsInterface())
  21428. {
  21429. if (methodDef->mIsOverride)
  21430. silentlyAllow = true;
  21431. }
  21432. else
  21433. {
  21434. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  21435. {
  21436. silentlyAllow = true;
  21437. methodInstance->mIsInnerOverride = true;
  21438. CheckOverridenMethod(methodInstance, checkMethodInstance);
  21439. }
  21440. else if (!checkMethod->mDeclaringType->IsExtension())
  21441. {
  21442. foundHiddenMethod = true;
  21443. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  21444. silentlyAllow = true;
  21445. else if (methodDef->mIsNew)
  21446. {
  21447. silentlyAllow = true;
  21448. }
  21449. else if (checkMethod->GetMethodDeclaration() == NULL)
  21450. silentlyAllow = true;
  21451. else if (methodDef->mIsOverride)
  21452. silentlyAllow = true;
  21453. else
  21454. extensionWarn = true;
  21455. }
  21456. else
  21457. silentlyAllow = true;
  21458. }
  21459. }
  21460. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  21461. silentlyAllow = true;
  21462. if (!silentlyAllow)
  21463. {
  21464. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  21465. {
  21466. auto refNode = methodDef->GetRefNode();
  21467. BfError* bfError;
  21468. if (extensionWarn)
  21469. {
  21470. if (methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject)
  21471. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  21472. StrFormat("This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional. Note that this method is not callable from project '%s'.",
  21473. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  21474. else
  21475. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  21476. "This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional.", refNode);
  21477. }
  21478. else
  21479. {
  21480. bfError = Fail(StrFormat("Method '%s' already declared with the same parameter types", MethodToString(checkMethodInstance).c_str()), refNode, true);
  21481. }
  21482. if ((bfError != NULL) && (checkMethod->GetRefNode() != refNode))
  21483. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  21484. }
  21485. }
  21486. }
  21487. }
  21488. }
  21489. }
  21490. // Virtual methods give their error while slotting
  21491. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  21492. (!methodDef->mIsLocalMethod) &&
  21493. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  21494. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  21495. {
  21496. auto baseType = typeInstance->mBaseType;
  21497. while (baseType != NULL)
  21498. {
  21499. auto baseTypeDef = baseType->mTypeDef;
  21500. baseTypeDef->PopulateMemberSets();
  21501. BfMethodDef* checkMethod = NULL;
  21502. BfMemberSetEntry* entry = NULL;
  21503. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21504. checkMethod = (BfMethodDef*)entry->mMemberDef;
  21505. while (checkMethod != NULL)
  21506. {
  21507. if (checkMethod->mMethodDeclaration == NULL)
  21508. {
  21509. checkMethod = checkMethod->mNextWithSameName;
  21510. continue;
  21511. }
  21512. if (baseType->mMethodInstanceGroups.size() == 0)
  21513. {
  21514. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  21515. break;
  21516. }
  21517. if (checkMethod == methodDef)
  21518. {
  21519. checkMethod = checkMethod->mNextWithSameName;
  21520. continue;
  21521. }
  21522. if (checkMethod->mName != methodDef->mName)
  21523. {
  21524. checkMethod = checkMethod->mNextWithSameName;
  21525. continue;
  21526. }
  21527. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  21528. if (checkMethodInstance != NULL)
  21529. {
  21530. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  21531. (checkMethod->mProtection != BfProtection_Private) &&
  21532. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  21533. {
  21534. if (!methodDef->mIsNew)
  21535. {
  21536. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  21537. if (refNode != NULL)
  21538. {
  21539. BfError* bfError = Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if the hiding was intentional.", TypeToString(baseType).c_str()), refNode); //CDH TODO should we mention override keyword in warning text?
  21540. if (bfError != NULL)
  21541. bfError->mIsPersistent = true;
  21542. }
  21543. }
  21544. foundHiddenMethod = true;
  21545. break;
  21546. }
  21547. }
  21548. checkMethod = checkMethod->mNextWithSameName;
  21549. }
  21550. if (foundHiddenMethod)
  21551. break;
  21552. baseType = baseType->mBaseType;
  21553. }
  21554. if ((methodDef->mIsNew) && (!foundHiddenMethod) && (!mCurTypeInstance->IsSpecializedType()))
  21555. {
  21556. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21557. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  21558. methodDeclaration->mNewSpecifier;
  21559. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  21560. }
  21561. }
  21562. }
  21563. if ((methodDef->mIsConcrete) && (!methodInstance->mIsForeignMethodDef) && (!mCurTypeInstance->IsInterface()))
  21564. {
  21565. Fail("Only interfaces methods can be declared as 'concrete'", methodDeclaration->mVirtualSpecifier);
  21566. }
  21567. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic) && (!methodInstance->mIsInnerOverride))
  21568. {
  21569. if ((virtualToken != NULL) && (virtualToken->mToken == BfToken_Override) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  21570. Fail("No suitable method found to override", virtualToken, true);
  21571. else
  21572. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  21573. }
  21574. else if (methodDef->mIsVirtual)
  21575. {
  21576. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  21577. Fail("Virtual or abstract members cannot be 'private'", virtualToken, true);
  21578. if ((methodDef->mProtection == BfProtection_Internal) && (virtualToken != NULL))
  21579. Fail("Virtual or abstract members cannot be 'internal'. Consider using the 'protected internal' access specifier.", virtualToken, true);
  21580. }
  21581. mCompiler->mStats.mMethodDeclarations++;
  21582. mCompiler->UpdateCompletion();
  21583. }
  21584. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  21585. {
  21586. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  21587. auto typeInstance = mCurTypeInstance;
  21588. auto methodDef = methodInstance->mMethodDef;
  21589. int virtualMethodMatchIdx = -1;
  21590. if (typeInstance->mHotTypeData != NULL)
  21591. {
  21592. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  21593. {
  21594. BF_ASSERT(mCompiler->IsHotCompile());
  21595. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  21596. // may slot this override anyway (?)
  21597. int vTableStart = 0;
  21598. auto implBaseType = typeInstance->GetImplBaseType();
  21599. if (implBaseType != NULL)
  21600. vTableStart = implBaseType->mVirtualMethodTableSize;
  21601. StringT<512> mangledName;
  21602. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  21603. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  21604. {
  21605. // O(1) checking when virtual methods haven't changed
  21606. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  21607. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  21608. if (mangledName == entry.mFuncName)
  21609. {
  21610. virtualMethodMatchIdx = vTableStart + checkIdx;
  21611. break;
  21612. }
  21613. }
  21614. if (virtualMethodMatchIdx != -1)
  21615. {
  21616. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21617. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  21618. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  21619. }
  21620. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  21621. }
  21622. }
  21623. if (virtualMethodMatchIdx == -1)
  21624. {
  21625. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  21626. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  21627. typeInstance->mVirtualMethodTable.push_back(entry);
  21628. }
  21629. }
  21630. void BfModule::CompareDeclTypes(BfTypeInstance* typeInst, BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  21631. {
  21632. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  21633. {
  21634. // When we provide an extension override in the same project a root type override
  21635. isBetter = true;
  21636. isWorse = false;
  21637. }
  21638. else
  21639. {
  21640. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  21641. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  21642. }
  21643. if ((isBetter == isWorse) && (typeInst != NULL) && (newDeclType->IsExtension()) && (prevDeclType->IsExtension()))
  21644. {
  21645. if ((typeInst->mGenericTypeInfo != NULL) && (typeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL))
  21646. {
  21647. isBetter = false;
  21648. isWorse = false;
  21649. auto newConstraints = typeInst->GetGenericParamsVector(newDeclType);
  21650. auto prevConstraints = typeInst->GetGenericParamsVector(prevDeclType);
  21651. for (int genericIdx = 0; genericIdx < (int)newConstraints->size(); genericIdx++)
  21652. {
  21653. auto newConstraint = (*newConstraints)[genericIdx];
  21654. auto prevConstraint = (*prevConstraints)[genericIdx];
  21655. bool newIsSubset = AreConstraintsSubset(newConstraint, prevConstraint);
  21656. bool prevIsSubset = AreConstraintsSubset(prevConstraint, newConstraint);
  21657. if ((prevIsSubset) && (!newIsSubset))
  21658. isBetter = true;
  21659. if ((!prevIsSubset) && (newIsSubset))
  21660. isWorse = true;
  21661. }
  21662. }
  21663. }
  21664. }
  21665. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  21666. {
  21667. BP_ZONE("BfModule::SlotVirtualMethod");
  21668. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  21669. return false;
  21670. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  21671. {
  21672. if (!mCompiler->mOptions.mAllowHotSwapping)
  21673. return;
  21674. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  21675. return;
  21676. if (methodInstance->mHotMethod == NULL)
  21677. CheckHotMethod(methodInstance, "");
  21678. if (methodInstance->mHotMethod == NULL)
  21679. return;
  21680. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  21681. if (declMethodInstance->mHotMethod == NULL)
  21682. CheckHotMethod(declMethodInstance, "");
  21683. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  21684. virtualDecl->mRefCount++;
  21685. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  21686. };
  21687. auto typeInstance = mCurTypeInstance;
  21688. auto typeDef = typeInstance->mTypeDef;
  21689. auto methodDef = methodInstance->mMethodDef;
  21690. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21691. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21692. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  21693. if (methodInstance->mIsInnerOverride)
  21694. return false;
  21695. BfAstNode* declaringNode = methodDeclaration;
  21696. if (propertyMethodDeclaration != NULL)
  21697. declaringNode = propertyMethodDeclaration->mNameNode;
  21698. BfMethodInstance* methodOverriden = NULL;
  21699. bool usedMethod = false;
  21700. BfTokenNode* virtualToken = NULL;
  21701. if (propertyDeclaration != NULL)
  21702. virtualToken = propertyDeclaration->mVirtualSpecifier;
  21703. else if (methodDeclaration != NULL)
  21704. virtualToken = methodDeclaration->mVirtualSpecifier;
  21705. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  21706. {
  21707. //Fail: Static members cannot be marked as override, virtual, or abstract
  21708. }
  21709. else if (methodDef->mIsVirtual)
  21710. {
  21711. if (IsHotCompile())
  21712. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  21713. BfTypeInstance* checkBase = typeInstance;
  21714. // If we are in an extension, look in ourselves first
  21715. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  21716. checkBase = checkBase->mBaseType;
  21717. if (typeInstance->IsValueType())
  21718. {
  21719. if (typeInstance->mBaseType == NULL)
  21720. return false; // It's actually ValueType
  21721. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  21722. if (!methodDef->mIsOverride)
  21723. {
  21724. Fail("Structs cannot have virtual methods", virtualToken, true);
  21725. return false;
  21726. }
  21727. checkBase = mContext->mBfObjectType;
  21728. if (checkBase->mVirtualMethodTableSize == 0)
  21729. PopulateType(checkBase, BfPopulateType_Full);
  21730. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  21731. return false; // System circular ref, don't do struct checking on those
  21732. }
  21733. int virtualMethodMatchIdx = -1;
  21734. bool hadHidingError = false;
  21735. BfMethodInstance* bestOverrideMethodInstance = NULL;
  21736. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  21737. int bestOverrideMethodIdx = -1;
  21738. int ambiguousOverrideMethodIdx = -1;
  21739. if (checkBase != NULL)
  21740. {
  21741. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  21742. auto lookupType = checkBase;
  21743. while (lookupType != NULL)
  21744. {
  21745. lookupType->mTypeDef->PopulateMemberSets();
  21746. BfMethodDef* nextMethodDef = NULL;
  21747. BfMemberSetEntry* entry;
  21748. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  21749. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  21750. while (nextMethodDef != NULL)
  21751. {
  21752. auto checkMethodDef = nextMethodDef;
  21753. nextMethodDef = nextMethodDef->mNextWithSameName;
  21754. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  21755. continue;
  21756. BfMethodInstance* baseMethodInstance = NULL;
  21757. int checkMethodIdx = -1;
  21758. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  21759. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  21760. {
  21761. if (lookupType->IsUnspecializedTypeVariation())
  21762. {
  21763. if (!lookupMethodInstance->mMethodDef->mIsOverride)
  21764. {
  21765. baseMethodInstance = lookupMethodInstance;
  21766. checkMethodIdx = -2;
  21767. }
  21768. }
  21769. if (baseMethodInstance == NULL)
  21770. continue;
  21771. }
  21772. if (baseMethodInstance == NULL)
  21773. {
  21774. checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  21775. if (checkMethodIdx >= baseVirtualMethodTable.mSize)
  21776. FatalError("SlotVirtualMethod OOB in baseVirtualMethodTable[checkMethodIdx]");
  21777. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  21778. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  21779. {
  21780. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  21781. continue;
  21782. }
  21783. baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21784. if (baseMethodInstance == NULL)
  21785. {
  21786. AssertErrorState();
  21787. continue;
  21788. }
  21789. }
  21790. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  21791. {
  21792. if (methodDef->mIsOverride)
  21793. {
  21794. BfMethodInstance* checkMethodInstance;
  21795. if (checkMethodIdx == -2)
  21796. checkMethodInstance = baseMethodInstance;
  21797. else if (typeInstance->IsValueType())
  21798. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21799. else
  21800. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21801. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  21802. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  21803. continue;
  21804. if (bestOverrideMethodInstance != NULL)
  21805. {
  21806. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  21807. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  21808. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  21809. if (isBetter == isWorse)
  21810. {
  21811. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  21812. }
  21813. else
  21814. {
  21815. if (isWorse)
  21816. continue;
  21817. ambiguousOverrideMethodInstance = NULL;
  21818. }
  21819. }
  21820. bestOverrideMethodInstance = checkMethodInstance;
  21821. bestOverrideMethodIdx = checkMethodIdx;
  21822. }
  21823. else
  21824. {
  21825. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  21826. {
  21827. if (!hadHidingError)
  21828. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  21829. hadHidingError = true;
  21830. }
  21831. }
  21832. }
  21833. }
  21834. lookupType = lookupType->mBaseType;
  21835. }
  21836. }
  21837. //TODO:
  21838. if ((checkBase != NULL)
  21839. && (false)
  21840. )
  21841. {
  21842. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  21843. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  21844. {
  21845. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  21846. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  21847. {
  21848. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  21849. continue;
  21850. }
  21851. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21852. if (baseMethodInstance == NULL)
  21853. {
  21854. AssertErrorState();
  21855. continue;
  21856. }
  21857. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  21858. {
  21859. if (methodDef->mIsOverride)
  21860. {
  21861. BfMethodInstance* checkMethodInstance;
  21862. if (typeInstance->IsValueType())
  21863. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21864. else
  21865. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21866. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  21867. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  21868. continue;
  21869. if (bestOverrideMethodInstance != NULL)
  21870. {
  21871. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  21872. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  21873. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  21874. if (isBetter == isWorse)
  21875. {
  21876. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  21877. }
  21878. else
  21879. {
  21880. if (isWorse)
  21881. continue;
  21882. ambiguousOverrideMethodInstance = NULL;
  21883. }
  21884. }
  21885. bestOverrideMethodInstance = checkMethodInstance;
  21886. bestOverrideMethodIdx = checkMethodIdx;
  21887. }
  21888. else
  21889. {
  21890. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  21891. {
  21892. if (!hadHidingError)
  21893. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  21894. hadHidingError = true;
  21895. }
  21896. }
  21897. }
  21898. }
  21899. }
  21900. if (bestOverrideMethodInstance != NULL)
  21901. {
  21902. if (ambiguousOverrideMethodInstance != NULL)
  21903. {
  21904. bool allow = false;
  21905. // If neither of these declarations "include" each other then it's okay. This can happen when we have two extensions that create the same virtual method but with different constraints.
  21906. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  21907. bool canSeeEachOther = false;
  21908. //
  21909. {
  21910. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  21911. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  21912. canSeeEachOther = true;
  21913. }
  21914. //
  21915. {
  21916. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  21917. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  21918. canSeeEachOther = true;
  21919. }
  21920. if (!canSeeEachOther)
  21921. {
  21922. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  21923. }
  21924. else
  21925. {
  21926. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  21927. if (error != NULL)
  21928. {
  21929. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  21930. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  21931. }
  21932. }
  21933. }
  21934. }
  21935. if (bestOverrideMethodIdx == -2)
  21936. {
  21937. // Comes from an unspecialized variation
  21938. virtualMethodMatchIdx = bestOverrideMethodIdx;
  21939. }
  21940. else if ((bestOverrideMethodInstance != NULL) && (bestOverrideMethodIdx != -1))
  21941. {
  21942. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  21943. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  21944. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  21945. {
  21946. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  21947. {
  21948. BfTypeReference* returnTypeRef;
  21949. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  21950. {
  21951. returnTypeRef = propertyDeclaration->mTypeRef;
  21952. Fail("Property differs from overridden property by type", returnTypeRef, true);
  21953. }
  21954. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21955. {
  21956. returnTypeRef = methodDeclaration->mReturnType;
  21957. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  21958. }
  21959. else
  21960. {
  21961. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  21962. }
  21963. return usedMethod;
  21964. }
  21965. }
  21966. if (methodDef->mIsOverride)
  21967. {
  21968. // We can have multiple matches when a virtual method is used to implement interface methods
  21969. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  21970. // vtable entries for this method signature
  21971. virtualMethodMatchIdx = bestOverrideMethodIdx;
  21972. if (!typeInstance->IsValueType())
  21973. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21974. if (typeInstance->IsValueType())
  21975. {
  21976. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  21977. }
  21978. else
  21979. {
  21980. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21981. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  21982. BfMethodInstance* setMethodInstance = methodInstance;
  21983. bool doOverride = false;
  21984. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  21985. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  21986. {
  21987. methodOverriden = overridenRef;
  21988. doOverride = true;
  21989. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  21990. {
  21991. bool isBetter = false;
  21992. bool isWorse = false;
  21993. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  21994. if (isBetter == isWorse)
  21995. {
  21996. // We have to resolve later per-project
  21997. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  21998. {
  21999. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22000. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  22001. }
  22002. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  22003. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  22004. doOverride = false;
  22005. }
  22006. else
  22007. {
  22008. if ((isBetter) && (ambiguityContext != NULL))
  22009. {
  22010. ambiguityContext->Remove(virtualMethodMatchIdx);
  22011. }
  22012. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  22013. {
  22014. if (preferRootDefinition)
  22015. {
  22016. // Leave the master GCMarkMember
  22017. isBetter = false;
  22018. isWorse = true;
  22019. }
  22020. }
  22021. doOverride = isBetter;
  22022. }
  22023. }
  22024. }
  22025. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  22026. {
  22027. methodOverriden = overridenRef;
  22028. doOverride = true;
  22029. }
  22030. if (doOverride)
  22031. {
  22032. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22033. _AddVirtualDecl(declMethodInstance);
  22034. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22035. auto& implMethodRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22036. if ((!mCompiler->mIsResolveOnly) && (implMethodRef.mMethodNum >= 0) &&
  22037. (implMethodRef.mTypeInstance == typeInstance) && (methodInstance->GetOwner() == typeInstance))
  22038. {
  22039. auto prevImplMethodInstance = (BfMethodInstance*)implMethodRef;
  22040. if (prevImplMethodInstance->mMethodDef->mDeclaringType->mProject != methodInstance->mMethodDef->mDeclaringType->mProject)
  22041. {
  22042. // We may need to have to previous method reified when we must re-slot in another project during vdata creation
  22043. BfReifyMethodDependency dep;
  22044. dep.mDepMethod = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22045. dep.mMethodIdx = implMethodRef.mMethodNum;
  22046. typeInstance->mReifyMethodDependencies.Add(dep);
  22047. }
  22048. if (!methodInstance->mMangleWithIdx)
  22049. {
  22050. // Keep mangled names from conflicting
  22051. methodInstance->mMangleWithIdx = true;
  22052. if ((methodInstance->mIRFunction) && (methodInstance->mDeclModule->mIsModuleMutable))
  22053. {
  22054. StringT<4096> mangledName;
  22055. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  22056. methodInstance->mDeclModule->mBfIRBuilder->SetFunctionName(methodInstance->mIRFunction, mangledName);
  22057. }
  22058. }
  22059. }
  22060. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  22061. }
  22062. }
  22063. if (methodOverriden != NULL)
  22064. {
  22065. CheckOverridenMethod(methodInstance, methodOverriden);
  22066. }
  22067. }
  22068. }
  22069. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  22070. {
  22071. if (methodDef->mIsOverride)
  22072. {
  22073. BfTokenNode* overrideToken = NULL;
  22074. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  22075. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  22076. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22077. overrideToken = methodDeclaration->mVirtualSpecifier;
  22078. if (overrideToken != NULL)
  22079. {
  22080. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  22081. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  22082. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  22083. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  22084. else
  22085. Fail("No suitable method found to override", overrideToken, true);
  22086. }
  22087. return usedMethod;
  22088. }
  22089. UniqueSlotVirtualMethod(methodInstance);
  22090. }
  22091. else
  22092. usedMethod = true;
  22093. if (typeInstance->IsValueType())
  22094. return usedMethod;
  22095. }
  22096. bool foundInterface = false;
  22097. bool hadAnyMatch = false;
  22098. // See if this method matches interfaces
  22099. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  22100. {
  22101. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  22102. if (ifaceInst->IsIncomplete())
  22103. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  22104. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  22105. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  22106. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  22107. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  22108. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  22109. continue;
  22110. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  22111. continue;
  22112. bool hadMatch = false;
  22113. BfMethodInstance* hadNameMatch = NULL;
  22114. BfType* expectedReturnType = NULL;
  22115. bool showedError = false;
  22116. // We go through our VTable looking for NULL entries within the interface sections
  22117. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  22118. // because a normal method declared in this type could have matched earlier
  22119. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  22120. ifaceInst->mTypeDef->PopulateMemberSets();
  22121. BfMethodDef* checkMethodDef = NULL;
  22122. BfMemberSetEntry* entry;
  22123. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  22124. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  22125. while (checkMethodDef != NULL)
  22126. {
  22127. int iMethodIdx = checkMethodDef->mIdx;
  22128. int iTableIdx = iMethodIdx + startIdx;
  22129. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  22130. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  22131. bool storeIFaceMethod = false;
  22132. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  22133. {
  22134. checkMethodDef = checkMethodDef->mNextWithSameName;
  22135. continue;
  22136. }
  22137. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  22138. auto iMethodInst = iMethodGroup.mDefault;
  22139. if (iMethodInst == NULL)
  22140. {
  22141. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  22142. AssertErrorState();
  22143. checkMethodDef = checkMethodDef->mNextWithSameName;
  22144. continue;
  22145. }
  22146. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  22147. hadNameMatch = iMethodInst;
  22148. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  22149. if ((!doesMethodSignatureMatch) && (interfaceMethodEntry->mMethodRef.IsNull()))
  22150. {
  22151. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  22152. }
  22153. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  22154. {
  22155. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  22156. {
  22157. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  22158. {
  22159. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  22160. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  22161. if (error != NULL)
  22162. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  22163. showedError = true;
  22164. }
  22165. }
  22166. }
  22167. if (doesMethodSignatureMatch)
  22168. {
  22169. usedMethod = true;
  22170. hadMatch = true;
  22171. hadAnyMatch = true;
  22172. storeIFaceMethod = true;
  22173. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  22174. {
  22175. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  22176. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance) && (!mIsComptimeModule))
  22177. {
  22178. // When autocompletion regenerates a single method body but not the whole type then
  22179. // we will see ourselves in the vtable already
  22180. return usedMethod;
  22181. }
  22182. bool isBetter = false;
  22183. bool isWorse = false;
  22184. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  22185. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  22186. if (isBetter == isWorse)
  22187. {
  22188. isBetter = methodInstance->mReturnType == iMethodInst->mReturnType;
  22189. isWorse = prevMethod->mReturnType == iMethodInst->mReturnType;
  22190. }
  22191. if (isBetter == isWorse)
  22192. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  22193. if (isBetter == isWorse)
  22194. {
  22195. if (ambiguityContext != NULL)
  22196. {
  22197. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  22198. }
  22199. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  22200. storeIFaceMethod = true;
  22201. }
  22202. else
  22203. {
  22204. if ((isBetter) && (ambiguityContext != NULL))
  22205. ambiguityContext->Remove(~iTableIdx);
  22206. storeIFaceMethod = isBetter;
  22207. }
  22208. }
  22209. }
  22210. if (storeIFaceMethod)
  22211. {
  22212. if (methodInstance->GetNumGenericParams() != 0)
  22213. _AddVirtualDecl(iMethodInst);
  22214. *iMethodPtr = methodInstance;
  22215. }
  22216. checkMethodDef = checkMethodDef->mNextWithSameName;
  22217. }
  22218. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  22219. {
  22220. if (expectedReturnType != NULL)
  22221. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  22222. else if (hadNameMatch != NULL)
  22223. {
  22224. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  22225. if (error != NULL)
  22226. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  22227. }
  22228. else
  22229. {
  22230. auto propertyDecl = methodDef->GetPropertyDeclaration();
  22231. if (propertyDecl != NULL)
  22232. {
  22233. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  22234. String name;
  22235. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  22236. name = "this[]";
  22237. else if (propertyDecl->mNameNode != NULL)
  22238. propertyDecl->mNameNode->ToString(name);
  22239. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  22240. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  22241. }
  22242. else
  22243. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  22244. }
  22245. }
  22246. }
  22247. // Any overriden virtual methods that were used in interfaces also need to be replaced
  22248. if (methodOverriden != NULL)
  22249. {
  22250. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  22251. {
  22252. if (methodEntry.mMethodRef == methodOverriden)
  22253. methodEntry.mMethodRef = methodInstance;
  22254. }
  22255. }
  22256. return usedMethod;
  22257. }
  22258. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  22259. {
  22260. auto methodDef = methodInstance->mMethodDef;
  22261. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  22262. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  22263. {
  22264. const char* protectionNames[] = { "hidden", "private", "internal", "protected", "protected internal", "public" };
  22265. BF_STATIC_ASSERT(BF_ARRAY_COUNT(protectionNames) == BfProtection_COUNT);
  22266. BfAstNode* protectionRefNode = NULL;
  22267. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  22268. {
  22269. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  22270. if (protectionRefNode == NULL)
  22271. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  22272. if (protectionRefNode == NULL)
  22273. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  22274. }
  22275. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22276. {
  22277. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  22278. if (protectionRefNode == NULL)
  22279. protectionRefNode = methodDeclaration->mNameNode;
  22280. }
  22281. if (protectionRefNode != NULL)
  22282. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  22283. }
  22284. }
  22285. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  22286. {
  22287. auto typeInstance = mCurTypeInstance;
  22288. auto methodDef = methodInstance->mMethodDef;
  22289. if (methodDef->mMethodType == BfMethodType_Ctor)
  22290. return true;
  22291. bool foundOverride = false;
  22292. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  22293. {
  22294. auto methodDeclaration = methodDef->GetMethodDeclaration();
  22295. BfAstNode* refNode = NULL;
  22296. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22297. refNode = propertyDeclaration->mProtectionSpecifier;
  22298. else if (methodDeclaration != NULL)
  22299. refNode = methodDeclaration->mProtectionSpecifier;
  22300. Fail("Private interface methods must provide a body", refNode);
  22301. }
  22302. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  22303. {
  22304. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  22305. }
  22306. BfAstNode* declaringNode = methodDef->GetRefNode();
  22307. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  22308. {
  22309. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  22310. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  22311. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  22312. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  22313. continue;
  22314. ifaceInst->mTypeDef->PopulateMemberSets();
  22315. BfMethodDef* nextMethod = NULL;
  22316. BfMemberSetEntry* entry = NULL;
  22317. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22318. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22319. while (nextMethod != NULL)
  22320. {
  22321. auto checkMethod = nextMethod;
  22322. nextMethod = nextMethod->mNextWithSameName;
  22323. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22324. if (ifaceMethod == NULL)
  22325. continue;
  22326. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22327. {
  22328. if (methodDef->mIsOverride)
  22329. {
  22330. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  22331. {
  22332. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  22333. if (error != NULL)
  22334. {
  22335. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  22336. }
  22337. }
  22338. foundOverride = true;
  22339. }
  22340. else if (!methodDef->mIsNew)
  22341. {
  22342. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  22343. }
  22344. }
  22345. }
  22346. }
  22347. if ((methodDef->mIsOverride) && (!foundOverride))
  22348. {
  22349. // This allows us to declare a method in the base definition or in an extension and then provide
  22350. // an implementation in a more-specific extension
  22351. typeInstance->mTypeDef->PopulateMemberSets();
  22352. BfMethodDef* nextMethod = NULL;
  22353. BfMemberSetEntry* entry = NULL;
  22354. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22355. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22356. while (nextMethod != NULL)
  22357. {
  22358. auto checkMethod = nextMethod;
  22359. nextMethod = nextMethod->mNextWithSameName;
  22360. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22361. if (ifaceMethod == NULL)
  22362. continue;
  22363. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  22364. continue;
  22365. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22366. {
  22367. foundOverride = true;
  22368. }
  22369. }
  22370. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  22371. // {
  22372. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  22373. // if (ifaceMethod == NULL)
  22374. // continue;
  22375. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  22376. // continue;
  22377. //
  22378. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22379. // {
  22380. // foundOverride = true;
  22381. // }
  22382. // }
  22383. }
  22384. if (methodDef->mIsOverride)
  22385. {
  22386. if (!foundOverride)
  22387. {
  22388. BfTokenNode* overrideToken = NULL;
  22389. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22390. overrideToken = propertyDeclaration->mVirtualSpecifier;
  22391. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22392. overrideToken = methodDeclaration->mVirtualSpecifier;
  22393. if (overrideToken != NULL)
  22394. {
  22395. Fail("No suitable method found to override", overrideToken, true);
  22396. }
  22397. else
  22398. {
  22399. // Possible cause - DTOR with params
  22400. AssertErrorState();
  22401. }
  22402. }
  22403. return true;
  22404. }
  22405. // Generic methods can't be called virtually
  22406. if (methodInstance->GetNumGenericParams() != 0)
  22407. return true;
  22408. // Only public methods can be called virtually
  22409. if (methodDef->mProtection != BfProtection_Public)
  22410. return true;
  22411. UniqueSlotVirtualMethod(methodInstance);
  22412. return true;
  22413. }
  22414. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  22415. {
  22416. if (methodInstance->mMethodInfoEx == NULL)
  22417. return;
  22418. int wantMinDepth = -1;
  22419. if (mCurTypeInstance != NULL)
  22420. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  22421. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  22422. {
  22423. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  22424. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  22425. wantMinDepth = wantTypeMinDepth;
  22426. }
  22427. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  22428. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  22429. }
  22430. void BfModule::DbgFinish()
  22431. {
  22432. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  22433. return;
  22434. if (mAwaitingInitFinish)
  22435. FinishInit();
  22436. if (mHasForceLinkMarker)
  22437. return;
  22438. String markerName;
  22439. BfIRValue linkMarker;
  22440. if (mBfIRBuilder->DbgHasInfo())
  22441. {
  22442. bool needForceLinking = false;
  22443. for (auto& ownedType : mOwnedTypeInstances)
  22444. {
  22445. bool hasConfirmedReference = false;
  22446. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  22447. {
  22448. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  22449. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  22450. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)) &&
  22451. (methodInstGroup.mHasEmittedReference))
  22452. {
  22453. hasConfirmedReference = true;
  22454. }
  22455. }
  22456. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  22457. needForceLinking = true;
  22458. }
  22459. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  22460. {
  22461. BfMethodState methodState;
  22462. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  22463. methodState.mTempKind = BfMethodState::TempKind_Static;
  22464. mHasForceLinkMarker = true;
  22465. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  22466. SizedArray<BfIRType, 0> paramTypes;
  22467. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  22468. String linkName = "FORCELINKMOD_" + mModuleName;
  22469. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  22470. mBfIRBuilder->SetActiveFunction(func);
  22471. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  22472. mBfIRBuilder->SetInsertPoint(entryBlock);
  22473. auto firstType = mOwnedTypeInstances[0];
  22474. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  22475. SizedArray<BfIRMDNode, 1> diParamTypes;
  22476. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  22477. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  22478. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  22479. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  22480. methodState.mCurScope->mDIScope = diScope;
  22481. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  22482. SizedArray<BfIRValue, 8> args;
  22483. BfExprEvaluator exprEvaluator(this);
  22484. for (auto& ownedType : mOwnedTypeInstances)
  22485. {
  22486. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  22487. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  22488. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  22489. }
  22490. mBfIRBuilder->CreateRetVoid();
  22491. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  22492. }
  22493. }
  22494. }
  22495. bool BfModule::Finish()
  22496. {
  22497. BP_ZONE("BfModule::Finish");
  22498. BfLogSysM("BfModule finish: %p\n", this);
  22499. if (mHadBuildError)
  22500. {
  22501. // Don't AssertErrorState here, this current pass may not have failed but
  22502. // the module was still queued in mFinishedModuleWorkList
  22503. ClearModule();
  22504. return true;
  22505. }
  22506. if (mUsedSlotCount != -1)
  22507. {
  22508. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  22509. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  22510. }
  22511. if ((!mGeneratesCode) && (!mAddedToCount))
  22512. return true;
  22513. BF_ASSERT(mAddedToCount);
  22514. mAddedToCount = false;
  22515. mAwaitingFinish = false;
  22516. mCompiler->mStats.mModulesFinished++;
  22517. if (HasCompiledOutput())
  22518. {
  22519. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  22520. DbgFinish();
  22521. if (mAwaitingInitFinish)
  22522. FinishInit();
  22523. for (auto ownedTypeInst : mOwnedTypeInstances)
  22524. {
  22525. // Generate dbg info and add global variables if we haven't already
  22526. mBfIRBuilder->PopulateType(ownedTypeInst);
  22527. }
  22528. if (mBfIRBuilder->DbgHasInfo())
  22529. {
  22530. mBfIRBuilder->DbgFinalize();
  22531. }
  22532. String objOutputPath;
  22533. String irOutputPath;
  22534. mIsModuleMutable = false;
  22535. //mOutFileNames.Clear();
  22536. BF_ASSERT(((int)mOutFileNames.size() >= mExtensionCount) || (mParentModule != NULL));
  22537. bool writeModule = mBfIRBuilder->HasExports();
  22538. String outputPath;
  22539. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  22540. auto& compilerOpts = mCompiler->mOptions;
  22541. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  22542. auto moduleOptions = GetModuleOptions();
  22543. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  22544. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  22545. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  22546. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  22547. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  22548. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  22549. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  22550. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  22551. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  22552. bool allowWriteToLib = true;
  22553. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  22554. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  22555. {
  22556. codeGenOptions.mWriteToLib = true;
  22557. mWroteToLib = true;
  22558. }
  22559. else
  22560. {
  22561. mWroteToLib = false;
  22562. }
  22563. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  22564. {
  22565. outputPath = mModuleName;
  22566. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  22567. BfModuleFileName moduleFileName;
  22568. if (mParentModule != NULL)
  22569. {
  22570. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  22571. {
  22572. if (checkPair.mValue == this)
  22573. moduleFileName.mProjects = checkPair.mKey;
  22574. }
  22575. }
  22576. moduleFileName.mProjects.Add(mProject);
  22577. if (fileIdx > 0)
  22578. outputPath += StrFormat("@%d", fileIdx + 1);
  22579. if (mCompiler->mOptions.mWriteIR)
  22580. irOutputPath = outputPath + ".ll";
  22581. if (mCompiler->mOptions.mGenerateObj)
  22582. {
  22583. objOutputPath = outputPath + BF_OBJ_EXT;
  22584. moduleFileName.mFileName = objOutputPath;
  22585. }
  22586. else if (mCompiler->mOptions.mWriteIR)
  22587. {
  22588. moduleFileName.mFileName = irOutputPath;
  22589. }
  22590. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  22591. {
  22592. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  22593. }
  22594. moduleFileName.mModuleWritten = writeModule;
  22595. moduleFileName.mWroteToLib = mWroteToLib;
  22596. if (!mOutFileNames.Contains(moduleFileName))
  22597. mOutFileNames.Add(moduleFileName);
  22598. }
  22599. if (mCompiler->IsHotCompile())
  22600. {
  22601. codeGenOptions.mIsHotCompile = true;
  22602. if (mParentModule != NULL)
  22603. mParentModule->mHadHotObjectWrites = true;
  22604. mHadHotObjectWrites = true;
  22605. }
  22606. //TODO: Testing VDATA
  22607. /*if (mModuleName == "vdata")
  22608. {
  22609. codeGenOptions.mOptLevel = 4;
  22610. }*/
  22611. codeGenOptions.GenerateHash();
  22612. BP_ZONE("BfModule::Finish.WriteObjectFile");
  22613. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  22614. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  22615. mLastModuleWrittenRevision = mCompiler->mRevision;
  22616. }
  22617. else
  22618. {
  22619. for (auto type : mOwnedTypeInstances)
  22620. {
  22621. BF_ASSERT((!type->IsIncomplete()) || (type->IsSpecializedByAutoCompleteMethod()));
  22622. }
  22623. }
  22624. for (auto& specModulePair : mSpecializedMethodModules)
  22625. {
  22626. auto specModule = specModulePair.mValue;
  22627. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  22628. {
  22629. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  22630. }
  22631. }
  22632. CleanupFileInstances();
  22633. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  22634. return true;
  22635. }
  22636. void BfModule::ReportMemory(MemReporter* memReporter)
  22637. {
  22638. memReporter->Add(sizeof(BfModule));
  22639. if (mBfIRBuilder != NULL)
  22640. {
  22641. memReporter->BeginSection("IRBuilder_ConstData");
  22642. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  22643. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  22644. memReporter->EndSection();
  22645. memReporter->BeginSection("IRBuilder_BFIR");
  22646. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  22647. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  22648. memReporter->EndSection();
  22649. memReporter->Add(sizeof(BfIRBuilder));
  22650. }
  22651. memReporter->BeginSection("FileInstanceMap");
  22652. memReporter->AddMap(mFileInstanceMap);
  22653. memReporter->AddMap(mNamedFileInstanceMap);
  22654. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  22655. memReporter->EndSection();
  22656. memReporter->AddVec(mOwnedTypeInstances, false);
  22657. memReporter->AddVec(mSpecializedMethodModules, false);
  22658. memReporter->AddVec(mOutFileNames, false);
  22659. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  22660. memReporter->AddMap(mInterfaceSlotRefs, false);
  22661. memReporter->AddMap(mStaticFieldRefs, false);
  22662. memReporter->AddMap(mClassVDataRefs, false);
  22663. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  22664. memReporter->AddMap(mTypeDataRefs, false);
  22665. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  22666. memReporter->AddMap(mDeferredMethodCallData, false);
  22667. memReporter->AddHashSet(mDeferredMethodIds, false);
  22668. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  22669. }
  22670. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  22671. // be transient through the next compile
  22672. void BfModule::ClearModuleData(bool clearTransientData)
  22673. {
  22674. BfLogSysM("ClearModuleData %p\n", this);
  22675. if (mAddedToCount)
  22676. {
  22677. mCompiler->mStats.mModulesFinished++;
  22678. mAddedToCount = false;
  22679. }
  22680. mDICompileUnit = BfIRMDNode();
  22681. if (clearTransientData)
  22682. mIncompleteMethodCount = 0;
  22683. mHasGenericMethods = false;
  22684. // We don't want to clear these because we want it to persist through module extensions-
  22685. // otherwise we may think an extension succeeds even though the base module failed
  22686. //mHadBuildError = false;
  22687. //mHadBuildWarning = false;
  22688. mClassVDataRefs.Clear();
  22689. mClassVDataExtRefs.Clear();
  22690. for (auto& kv : mTypeDataRefs)
  22691. kv.mValue = BfIRValue();
  22692. mStringCharPtrPool.Clear();
  22693. mStringObjectPool.Clear();
  22694. mStaticFieldRefs.Clear();
  22695. BF_ASSERT(!mIgnoreErrors);
  22696. for (auto prevIRBuilder : mPrevIRBuilders)
  22697. delete prevIRBuilder;
  22698. mPrevIRBuilders.Clear();
  22699. for (auto& specPair : mSpecializedMethodModules)
  22700. {
  22701. auto specModule = specPair.mValue;
  22702. specModule->ClearModuleData();
  22703. }
  22704. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  22705. mBuiltInFuncs[i] = BfIRFunction();
  22706. if (mNextAltModule != NULL)
  22707. mNextAltModule->ClearModuleData();
  22708. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  22709. mIsModuleMutable = false;
  22710. delete mBfIRBuilder;
  22711. mBfIRBuilder = NULL;
  22712. mWantsIRIgnoreWrites = false;
  22713. }
  22714. void BfModule::DisownMethods()
  22715. {
  22716. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  22717. mBuiltInFuncs[i] = BfIRFunction();
  22718. BfModule* methodModule = this;
  22719. if (mParentModule != NULL)
  22720. methodModule = mParentModule;
  22721. for (auto typeInst : methodModule->mOwnedTypeInstances)
  22722. {
  22723. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  22724. {
  22725. if (methodGroup.mDefault != NULL)
  22726. {
  22727. if (methodGroup.mDefault->mIRFunction)
  22728. {
  22729. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  22730. if (methodGroup.mDefault->mDeclModule == this)
  22731. {
  22732. methodGroup.mDefault->mIRFunction = BfIRFunction();
  22733. }
  22734. }
  22735. }
  22736. if (methodGroup.mMethodSpecializationMap != NULL)
  22737. {
  22738. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  22739. {
  22740. auto methodInstance = mapPair.mValue;
  22741. if (methodInstance->mDeclModule == this)
  22742. {
  22743. methodInstance->mIRFunction = BfIRFunction();
  22744. }
  22745. }
  22746. }
  22747. }
  22748. }
  22749. }
  22750. void BfModule::ClearModule()
  22751. {
  22752. ClearModuleData();
  22753. DisownMethods();
  22754. for (auto& specPair : mSpecializedMethodModules)
  22755. {
  22756. auto specModule = specPair.mValue;
  22757. specModule->ClearModule();
  22758. }
  22759. if (mNextAltModule != NULL)
  22760. mNextAltModule->ClearModule();
  22761. }