BfModule.cpp 865 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371
  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. for (int i = 0; i < (int)mAssignedLocals.size(); )
  118. {
  119. auto& local = mAssignedLocals[i];
  120. bool wantRemove = true;
  121. bool foundOtherFields = false;
  122. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  123. {
  124. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  125. {
  126. if ((otherLocalAssignData.mLocalVarField == local.mLocalVarField) || (otherLocalAssignData.mLocalVarField == -1))
  127. {
  128. if (otherLocalAssignData.mAssignKind == BfLocalVarAssignKind_Conditional)
  129. local.mAssignKind = BfLocalVarAssignKind_Conditional;
  130. wantRemove = false;
  131. }
  132. else
  133. foundOtherFields = true;
  134. }
  135. }
  136. if ((wantRemove) && (foundOtherFields))
  137. {
  138. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  139. {
  140. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  141. {
  142. mAssignedLocals.Add(otherLocalAssignData);
  143. }
  144. }
  145. }
  146. if (wantRemove)
  147. {
  148. mAssignedLocals.RemoveAt(i);
  149. }
  150. else
  151. i++;
  152. }
  153. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  154. }
  155. void BfDeferredLocalAssignData::Validate() const
  156. {
  157. for (auto var : mAssignedLocals)
  158. {
  159. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  160. }
  161. }
  162. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  163. {
  164. BreakExtendChain();
  165. Validate();
  166. otherLocalAssignData.Validate();
  167. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  168. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  169. {
  170. if (!mAssignedLocals.Contains(*otherItr))
  171. mAssignedLocals.push_back(*otherItr);
  172. ++otherItr;
  173. }
  174. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  175. }
  176. BfMethodState::~BfMethodState()
  177. {
  178. BF_ASSERT(mPendingNullConditional == NULL);
  179. if (mPrevMethodState != NULL)
  180. {
  181. BF_ASSERT(mCurAccessId == 1);
  182. BF_ASSERT(mCurLocalVarId <= 0);
  183. }
  184. for (auto local : mLocals)
  185. delete local;
  186. for (auto& kv : mLambdaCache)
  187. delete kv.mValue;
  188. }
  189. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  190. {
  191. auto checkMethodState = this;
  192. while (checkMethodState != NULL)
  193. {
  194. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  195. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  196. return checkMethodState;
  197. checkMethodState = checkMethodState->mPrevMethodState;
  198. }
  199. BF_FATAL("Failed to find method state for localvar");
  200. return NULL;
  201. }
  202. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx, BfLocalVarAssignKind assignKind, bool isFromDeferredAssignData)
  203. {
  204. auto localVarMethodState = GetMethodStateForLocal(localVar);
  205. if (localVarMethodState != this)
  206. {
  207. return;
  208. }
  209. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  210. {
  211. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  212. // 'a' is always defined, but 'b' isn't:
  213. // if (Check(out a) || Check(out b)) { } int z = a;
  214. auto deferredLocalAssignData = mDeferredLocalAssignData;
  215. if ((deferredLocalAssignData != NULL) &&
  216. (deferredLocalAssignData->mIsIfCondition) &&
  217. (!deferredLocalAssignData->mIfMayBeSkipped))
  218. {
  219. ifDeferredLocalAssignData = deferredLocalAssignData;
  220. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  221. }
  222. while ((deferredLocalAssignData != NULL) &&
  223. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  224. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  225. if (assignKind == BfLocalVarAssignKind_None)
  226. assignKind = ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mLeftBlock)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  227. if (localVar->mAssignedKind >= assignKind)
  228. {
  229. // Leave it alone
  230. }
  231. else if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  232. {
  233. if (fieldIdx >= 0)
  234. {
  235. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  236. if (localVar->mUnassignedFieldFlags == 0)
  237. {
  238. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  239. localVar->mAssignedKind = assignKind;
  240. }
  241. }
  242. else
  243. {
  244. localVar->mAssignedKind = assignKind;
  245. }
  246. }
  247. else
  248. {
  249. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  250. BfAssignedLocal defineVal = {localVar, fieldIdx, assignKind};
  251. if (!deferredLocalAssignData->Contains(defineVal))
  252. deferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  253. if (ifDeferredLocalAssignData != NULL)
  254. {
  255. if (!ifDeferredLocalAssignData->Contains(defineVal))
  256. ifDeferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  257. }
  258. }
  259. }
  260. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  261. }
  262. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  263. {
  264. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  265. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  266. {
  267. LocalDefined(assignedLocal.mLocalVar, assignedLocal.mLocalVarField, assignedLocal.mAssignKind, true);
  268. }
  269. }
  270. void BfMethodState::Reset()
  271. {
  272. mHeadScope.mDeferredCallEntries.DeleteAll();
  273. }
  274. //////////////////////////////////////////////////////////////////////////
  275. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  276. {
  277. Entry* entry = NULL;
  278. if (mEntries.TryAdd(id, NULL, &entry))
  279. {
  280. entry->mInterfaceEntry = interfaceEntry;
  281. entry->mMethodIdx = methodIdx;
  282. }
  283. if (!entry->mCandidates.Contains(candidateA))
  284. entry->mCandidates.push_back(candidateA);
  285. if (!entry->mCandidates.Contains(candidateB))
  286. entry->mCandidates.push_back(candidateB);
  287. }
  288. void BfAmbiguityContext::Remove(int id)
  289. {
  290. mEntries.Remove(id);
  291. }
  292. void BfAmbiguityContext::Finish()
  293. {
  294. for (auto& entryPair : mEntries)
  295. {
  296. int id = entryPair.mKey;
  297. auto entry = &entryPair.mValue;
  298. if (id >= 0)
  299. {
  300. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  301. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  302. for (auto candidate : entry->mCandidates)
  303. {
  304. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  305. }
  306. }
  307. else
  308. {
  309. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  310. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  311. for (auto candidate : entry->mCandidates)
  312. {
  313. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  314. }
  315. }
  316. }
  317. }
  318. //////////////////////////////////////////////////////////////////////////
  319. class HasAppendAllocVisitor : BfElementVisitor
  320. {
  321. public:
  322. bool mHas;
  323. public:
  324. HasAppendAllocVisitor()
  325. {
  326. mHas = false;
  327. }
  328. void Visit(BfObjectCreateExpression* objCreateExpr)
  329. {
  330. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  331. {
  332. if (newToken->GetToken() == BfToken_Append)
  333. {
  334. mHas = true;
  335. }
  336. }
  337. }
  338. bool HasAppendAlloc(BfAstNode* node)
  339. {
  340. mHas = false;
  341. VisitChild(node);
  342. return mHas;
  343. }
  344. };
  345. class AppendAllocVisitor : public BfStructuralVisitor
  346. {
  347. public:
  348. BfModule* mModule;
  349. HasAppendAllocVisitor mHasAppendAllocVisitor;
  350. BfTypedValue mConstAccum;
  351. bool mFailed;
  352. bool mIsFirstConstPass;
  353. int mCurAppendAlign;
  354. public:
  355. AppendAllocVisitor()
  356. {
  357. mFailed = false;
  358. mIsFirstConstPass = false;
  359. mCurAppendAlign = 1;
  360. }
  361. void EmitAppendAlign(int align, int sizeMultiple = 0)
  362. {
  363. BF_ASSERT(align > 0);
  364. if (mIsFirstConstPass)
  365. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  366. if (sizeMultiple == 0)
  367. sizeMultiple = align;
  368. if (mCurAppendAlign == 0)
  369. mCurAppendAlign = sizeMultiple;
  370. else
  371. {
  372. if (sizeMultiple % align == 0)
  373. mCurAppendAlign = align;
  374. else
  375. mCurAppendAlign = sizeMultiple % align;
  376. }
  377. BF_ASSERT(mCurAppendAlign > 0);
  378. if (mConstAccum)
  379. {
  380. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  381. if (constant != NULL)
  382. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  383. else
  384. BF_ASSERT(mIsFirstConstPass);
  385. return;
  386. }
  387. mModule->EmitAppendAlign(align, sizeMultiple);
  388. }
  389. void Visit(BfAstNode* astNode) override
  390. {
  391. mModule->VisitChild(astNode);
  392. }
  393. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  394. {
  395. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  396. {
  397. if (newToken->GetToken() == BfToken_Append)
  398. {
  399. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  400. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  401. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  402. BfArrayType* arrayType = NULL;
  403. bool isArrayAlloc = false;
  404. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  405. SizedArray<BfIRValue, 2> dimLengthVals;
  406. BfType* origResolvedTypeRef = NULL;
  407. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  408. {
  409. if (variableDecl != NULL)
  410. {
  411. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  412. if (origResolvedTypeRef->IsObject())
  413. {
  414. if (origResolvedTypeRef->IsArray())
  415. {
  416. arrayType = (BfArrayType*)origResolvedTypeRef;
  417. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  418. isArrayAlloc = true;
  419. }
  420. }
  421. else if (origResolvedTypeRef->IsPointer())
  422. {
  423. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  424. }
  425. }
  426. }
  427. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  428. {
  429. isArrayAlloc = true;
  430. bool handled = false;
  431. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  432. {
  433. if (variableDecl->mTypeRef != NULL)
  434. {
  435. auto variableType = mModule->ResolveTypeRef(variableDecl->mTypeRef);
  436. if (variableType != NULL)
  437. {
  438. if (variableType->IsArray())
  439. origResolvedTypeRef = variableType->GetUnderlyingType();
  440. }
  441. handled = true;
  442. }
  443. }
  444. if (!handled)
  445. {
  446. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  447. }
  448. if (origResolvedTypeRef == NULL)
  449. {
  450. mModule->AssertErrorState();
  451. return;
  452. }
  453. int dimensions = 1;
  454. if (arrayTypeRef->mParams.size() != 0)
  455. {
  456. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  457. for (auto arg : arrayTypeRef->mParams)
  458. {
  459. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  460. {
  461. if (tokenNode->GetToken() == BfToken_Comma)
  462. {
  463. if (isRawArrayAlloc)
  464. {
  465. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  466. continue;
  467. }
  468. dimensions++;
  469. continue;
  470. }
  471. }
  472. auto expr = BfNodeDynCast<BfExpression>(arg);
  473. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  474. {
  475. mModule->CreateValueFromExpression(expr, intType);
  476. continue;
  477. }
  478. BfTypedValue dimLength;
  479. if (expr == NULL)
  480. {
  481. // Not specified
  482. dimLengthVals.push_back(BfIRValue());
  483. continue;
  484. }
  485. if (arg != NULL)
  486. dimLength = mModule->CreateValueFromExpression(expr, intType);
  487. if (!dimLength)
  488. {
  489. dimLength = mModule->GetDefaultTypedValue(intType);
  490. }
  491. dimLengthVals.push_back(dimLength.mValue);
  492. }
  493. }
  494. if (!isRawArrayAlloc)
  495. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  496. }
  497. if (origResolvedTypeRef == NULL)
  498. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  499. if (origResolvedTypeRef == NULL)
  500. {
  501. mModule->AssertErrorState();
  502. return;
  503. }
  504. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  505. auto resolvedTypeRef = origResolvedTypeRef;
  506. auto resultType = resolvedTypeRef;
  507. BfIRValue sizeValue;
  508. int curAlign = 0;
  509. if (isArrayAlloc)
  510. {
  511. int dimensions = 1;
  512. if (arrayType != NULL)
  513. dimensions = arrayType->mDimensions;
  514. bool sizeFailed = false;
  515. //
  516. {
  517. BfAstNode* initNode = objCreateExpr;
  518. for (int dim = 0; dim < dimensions; dim++)
  519. {
  520. BfAstNode* nextInitNode = NULL;
  521. int dimSize = -1;
  522. if (initNode == objCreateExpr)
  523. {
  524. dimSize = objCreateExpr->mArguments.size();
  525. if (!objCreateExpr->mArguments.IsEmpty())
  526. nextInitNode = objCreateExpr->mArguments[0];
  527. }
  528. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  529. {
  530. dimSize = (int)tupleNode->mCommas.size() + 1;
  531. }
  532. if (dimSize >= 0)
  533. {
  534. if (dim >= dimLengthVals.size())
  535. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  536. }
  537. else
  538. {
  539. sizeFailed = true;
  540. }
  541. }
  542. }
  543. BfIRValue allocCount;
  544. if (!sizeFailed)
  545. {
  546. if (!dimLengthVals.IsEmpty())
  547. {
  548. allocCount = dimLengthVals[0];
  549. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  550. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  551. }
  552. }
  553. if (!allocCount)
  554. {
  555. mFailed = true;
  556. if (!mIsFirstConstPass)
  557. {
  558. if (!mConstAccum)
  559. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  560. return;
  561. }
  562. }
  563. mModule->PopulateType(resultType);
  564. if (isRawArrayAlloc)
  565. {
  566. curAlign = resultType->mAlign;
  567. EmitAppendAlign(resultType->mAlign);
  568. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  569. }
  570. else
  571. {
  572. if (arrayType == NULL)
  573. arrayType = mModule->CreateArrayType(resultType, 1);
  574. // Array is a special case where the total size isn't aligned with mAlign
  575. // since we add arbitrary elements to the end without padding the end to align
  576. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  577. curAlign = arrayType->mAlign;
  578. auto firstElementField = &arrayType->mFieldInstances.back();
  579. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  580. sizeValue = mModule->GetConstValue(arrayClassSize);
  581. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  582. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  583. }
  584. }
  585. else
  586. {
  587. auto typeInst = resultType->ToTypeInstance();
  588. if (typeInst != NULL)
  589. {
  590. curAlign = typeInst->mInstAlign;
  591. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  592. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  593. }
  594. else
  595. {
  596. curAlign = resultType->mAlign;
  597. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  598. sizeValue = mModule->GetConstValue(resultType->mSize);
  599. }
  600. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  601. BfExprEvaluator exprEvaluator(mModule);
  602. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  603. BfFunctionBindResult bindResult;
  604. bindResult.mWantsArgs = true;
  605. exprEvaluator.mFunctionBindResult = &bindResult;
  606. SizedArray<BfExpression*, 8> copiedArgs;
  607. for (BfExpression* arg : objCreateExpr->mArguments)
  608. copiedArgs.push_back(arg);
  609. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  610. BfResolvedArgs argValues(&sizedArgExprs);
  611. if (typeInst != NULL)
  612. {
  613. exprEvaluator.ResolveArgValues(argValues);
  614. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  615. }
  616. exprEvaluator.mFunctionBindResult = NULL;
  617. if (bindResult.mMethodInstance != NULL)
  618. {
  619. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  620. {
  621. auto calcAppendArgs = bindResult.mIRArgs;
  622. BF_ASSERT(calcAppendArgs[0].IsFake());
  623. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  624. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  625. auto subDependSize = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, calcAppendArgs);
  626. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  627. {
  628. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  629. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  630. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  631. }
  632. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  633. if ((!subDependSize) && (!mConstAccum))
  634. {
  635. BF_ASSERT(calcAppendMethodModule.mFunc);
  636. subDependSize = exprEvaluator.CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  637. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  638. }
  639. if (subDependSize)
  640. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  641. else
  642. mFailed = true;
  643. }
  644. }
  645. }
  646. if (sizeValue)
  647. {
  648. if (mConstAccum)
  649. {
  650. if (!sizeValue.IsConst())
  651. {
  652. mFailed = true;
  653. if (!mIsFirstConstPass)
  654. return;
  655. }
  656. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  657. }
  658. else
  659. {
  660. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  661. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  662. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  663. }
  664. }
  665. }
  666. }
  667. }
  668. void Visit(BfObjectCreateExpression* objCreateExpr) override
  669. {
  670. DoObjectCreate(objCreateExpr, NULL);
  671. }
  672. void Visit(BfVariableDeclaration* varDecl) override
  673. {
  674. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  675. {
  676. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  677. DoObjectCreate(objectCreateExpr, varDecl);
  678. else
  679. VisitChild(varDecl->mInitializer);
  680. if (varDecl->mNameNode != NULL)
  681. {
  682. BfLocalVariable* localDef = new BfLocalVariable();
  683. localDef->mName = varDecl->mNameNode->ToString();
  684. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  685. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  686. localDef->mIsReadOnly = true;
  687. localDef->mParamFailed = true;
  688. localDef->mReadFromId = 0;
  689. mModule->AddLocalVariableDef(localDef);
  690. }
  691. }
  692. else
  693. {
  694. mModule->Visit(varDecl);
  695. }
  696. }
  697. void Visit(BfExpressionStatement* exprStatement) override
  698. {
  699. VisitChild(exprStatement->mExpression);
  700. }
  701. // void Visit(BfIfStatement* ifStmt) override
  702. // {
  703. // mModule->DoIfStatement(ifStmt,
  704. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  705. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  706. // }
  707. void Visit(BfBlock* block) override
  708. {
  709. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  710. return;
  711. int appendAllocIdx = -1;
  712. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  713. {
  714. auto child = block->mChildArr.mVals[childIdx];
  715. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  716. {
  717. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  718. {
  719. auto emitChild = block->mChildArr.mVals[emitIdx];
  720. mModule->UpdateSrcPos(emitChild);
  721. VisitChild(emitChild);
  722. if ((mFailed) && (!mIsFirstConstPass))
  723. break;
  724. }
  725. break;
  726. }
  727. }
  728. }
  729. };
  730. //////////////////////////////////////////////////////////////////////////
  731. BfModule* gLastCreatedModule = NULL;
  732. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  733. {
  734. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  735. gLastCreatedModule = this;
  736. mContext = context;
  737. mModuleName = moduleName;
  738. if (!moduleName.empty())
  739. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  740. mAddedToCount = false;
  741. mParentModule = NULL;
  742. mNextAltModule = NULL;
  743. mBfIRBuilder = NULL;
  744. mWantsIRIgnoreWrites = false;
  745. mModuleOptions = NULL;
  746. mLastUsedRevision = -1;
  747. mUsedSlotCount = -1;
  748. mIsReified = true;
  749. mGeneratesCode = true;
  750. mReifyQueued = false;
  751. mIsSpecialModule = false;
  752. mIsComptimeModule = false;
  753. mIsScratchModule = false;
  754. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  755. mHadBuildError = false;
  756. mHadBuildWarning = false;
  757. mIgnoreErrors = false;
  758. mHadIgnoredError = false;
  759. mIgnoreWarnings = false;
  760. mReportErrors = true;
  761. mIsInsideAutoComplete = false;
  762. mIsDeleting = false;
  763. mSkipInnerLookup = false;
  764. mIsHotModule = false;
  765. mSetIllegalSrcPosition = false;
  766. mNoResolveGenericParams = false;
  767. mWroteToLib = false;
  768. mContext = context;
  769. mCompiler = context->mCompiler;
  770. mSystem = mCompiler->mSystem;
  771. mProject = NULL;
  772. mCurMethodState = NULL;
  773. mAttributeState = NULL;
  774. mCurLocalMethodId = 0;
  775. mParentNodeEntry = NULL;
  776. mRevision = -1;
  777. mRebuildIdx = 0;
  778. mLastModuleWrittenRevision = 0;
  779. mIsModuleMutable = false;
  780. mExtensionCount = 0;
  781. mIncompleteMethodCount = 0;
  782. mOnDemandMethodCount = 0;
  783. mHasGenericMethods = false;
  784. mCurMethodInstance = NULL;
  785. mCurTypeInstance = NULL;
  786. mAwaitingInitFinish = false;
  787. mAwaitingFinish = false;
  788. mHasFullDebugInfo = false;
  789. mHadHotObjectWrites = false;
  790. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  791. mBuiltInFuncs[i] = BfIRFunction();
  792. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  793. }
  794. void BfReportMemory();
  795. BfModule::~BfModule()
  796. {
  797. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  798. if (!mIsDeleting)
  799. RemoveModuleData();
  800. }
  801. void BfModule::RemoveModuleData()
  802. {
  803. BF_ASSERT(!mIsDeleting);
  804. if (!mModuleName.empty())
  805. {
  806. // Note: module names not necessarily unique
  807. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  808. }
  809. CleanupFileInstances();
  810. delete mBfIRBuilder;
  811. mBfIRBuilder = NULL;
  812. //delete mCpu;
  813. for (auto prevModule : mPrevIRBuilders)
  814. delete prevModule;
  815. mPrevIRBuilders.Clear();
  816. for (auto& pairVal : mDeferredMethodCallData)
  817. delete pairVal.mValue;
  818. mDeferredMethodCallData.Clear();
  819. mDeferredMethodIds.Clear();
  820. for (auto& specModulePair : mSpecializedMethodModules)
  821. delete specModulePair.mValue;
  822. mSpecializedMethodModules.Clear();
  823. if (mNextAltModule != NULL)
  824. delete mNextAltModule;
  825. mNextAltModule = NULL;
  826. if (mModuleOptions != NULL)
  827. delete mModuleOptions;
  828. mModuleOptions = NULL;
  829. BfReportMemory();
  830. }
  831. void BfModule::Init(bool isFullRebuild)
  832. {
  833. mContext->mFinishedModuleWorkList.Remove(this);
  834. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  835. BF_ASSERT(mIsReified);
  836. if (!mIsScratchModule)
  837. {
  838. mCompiler->mStats.mModulesStarted++;
  839. if (mIsReified)
  840. mCompiler->mStats.mReifiedModuleCount++;
  841. mAddedToCount = true;
  842. }
  843. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  844. mFuncReferences.Clear();
  845. mClassVDataRefs.Clear();
  846. mClassVDataExtRefs.Clear();
  847. //mTypeDataRefs.Clear();
  848. mDbgRawAllocDataRefs.Clear();
  849. CleanupFileInstances();
  850. mStaticFieldRefs.Clear();
  851. //mInterfaceSlotRefs.Clear();
  852. // If we are just doing an extension then the ownede types aren't rebuilt.
  853. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  854. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  855. if (isFullRebuild)
  856. mRevision = mCompiler->mRevision;
  857. BF_ASSERT(mCurTypeInstance == NULL);
  858. mIsModuleMutable = true;
  859. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  860. if (!mIsComptimeModule)
  861. {
  862. #ifdef _DEBUG
  863. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  864. #else
  865. EnsureIRBuilder(false);
  866. #endif
  867. }
  868. mCurMethodState = NULL;
  869. mAwaitingInitFinish = true;
  870. mOnDemandMethodCount = 0;
  871. mAwaitingFinish = false;
  872. mHasForceLinkMarker = false;
  873. mUsedSlotCount = -1;
  874. }
  875. bool BfModule::WantsFinishModule()
  876. {
  877. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  878. }
  879. bool BfModule::IsHotCompile()
  880. {
  881. return mCompiler->IsHotCompile() && !mIsComptimeModule;
  882. }
  883. void BfModule::FinishInit()
  884. {
  885. BF_ASSERT(mAwaitingInitFinish);
  886. auto moduleOptions = GetModuleOptions();
  887. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  888. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple, mCompiler->mOptions.mTargetCPU);
  889. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  890. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  891. {
  892. // Og+ requires debug info
  893. moduleOptions.mEmitDebugInfo = 1;
  894. }
  895. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  896. if (mIsComptimeModule)
  897. mHasFullDebugInfo = true;
  898. if (((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified)) ||
  899. (mIsComptimeModule))
  900. {
  901. mBfIRBuilder->DbgInit();
  902. }
  903. else
  904. mHasFullDebugInfo = false;
  905. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  906. ((moduleOptions.mEmitDebugInfo != 0)))
  907. {
  908. if (mCompiler->mOptions.IsCodeView())
  909. {
  910. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  911. }
  912. else
  913. {
  914. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  915. }
  916. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  917. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  918. }
  919. mAwaitingInitFinish = false;
  920. }
  921. void BfModule::CalcGeneratesCode()
  922. {
  923. if ((!mIsReified) || (mIsScratchModule))
  924. {
  925. mGeneratesCode = false;
  926. return;
  927. }
  928. mGeneratesCode = false;
  929. for (auto typeInst : mOwnedTypeInstances)
  930. if (!typeInst->IsInterface())
  931. mGeneratesCode = true;
  932. }
  933. void BfModule::ReifyModule()
  934. {
  935. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  936. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  937. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  938. mIsReified = true;
  939. CalcGeneratesCode();
  940. mReifyQueued = false;
  941. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  942. mCompiler->mStats.mModulesReified++;
  943. }
  944. void BfModule::UnreifyModule()
  945. {
  946. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  947. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  948. mIsReified = false;
  949. CalcGeneratesCode();
  950. mReifyQueued = false;
  951. StartNewRevision(RebuildKind_None, true);
  952. mCompiler->mStats.mModulesUnreified++;
  953. }
  954. void BfModule::CleanupFileInstances()
  955. {
  956. for (auto& itr : mNamedFileInstanceMap)
  957. {
  958. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  959. delete itr.mValue;
  960. }
  961. mCurFilePosition.mFileInstance = NULL;//
  962. mFileInstanceMap.Clear();
  963. mNamedFileInstanceMap.Clear();
  964. }
  965. void BfModule::Cleanup()
  966. {
  967. CleanupFileInstances();
  968. }
  969. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  970. {
  971. if (HasCompiledOutput())
  972. {
  973. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  974. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  975. {
  976. StartExtension();
  977. }
  978. }
  979. else
  980. {
  981. EnsureIRBuilder();
  982. }
  983. }
  984. void BfModule::SetupIRBuilder(bool dbgVerifyCodeGen)
  985. {
  986. if (mIsScratchModule)
  987. {
  988. mBfIRBuilder->mIgnoreWrites = true;
  989. BF_ASSERT(!dbgVerifyCodeGen);
  990. }
  991. #ifdef _DEBUG
  992. if (mCompiler->mIsResolveOnly)
  993. {
  994. // For "deep" verification testing
  995. /*if (!mIsSpecialModule)
  996. dbgVerifyCodeGen = true;*/
  997. // We only want to turn this off on smaller builds for testing
  998. mBfIRBuilder->mIgnoreWrites = true;
  999. if (dbgVerifyCodeGen)
  1000. mBfIRBuilder->mIgnoreWrites = false;
  1001. if (!mBfIRBuilder->mIgnoreWrites)
  1002. {
  1003. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  1004. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1005. }
  1006. }
  1007. else if (!mGeneratesCode)
  1008. {
  1009. mBfIRBuilder->mIgnoreWrites = true;
  1010. }
  1011. else
  1012. {
  1013. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  1014. // code as we walk the AST
  1015. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1016. if (
  1017. (mModuleName == "-")
  1018. //|| (mModuleName == "BeefTest2_ClearColorValue")
  1019. //|| (mModuleName == "Tests_FuncRefs")
  1020. )
  1021. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1022. // Just for testing!
  1023. //mBfIRBuilder->mIgnoreWrites = true;
  1024. }
  1025. #else
  1026. if (mCompiler->mIsResolveOnly)
  1027. {
  1028. // Always ignore writes in resolveOnly for release builds
  1029. mBfIRBuilder->mIgnoreWrites = true;
  1030. }
  1031. else
  1032. {
  1033. // Just for memory testing! This breaks everything.
  1034. //mBfIRBuilder->mIgnoreWrites = true;
  1035. // For "deep" verification testing
  1036. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1037. }
  1038. #endif
  1039. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  1040. }
  1041. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  1042. {
  1043. BF_ASSERT(!mIsDeleting);
  1044. if (mBfIRBuilder == NULL)
  1045. {
  1046. if ((!mIsScratchModule) && (!mAddedToCount))
  1047. {
  1048. mCompiler->mStats.mModulesStarted++;
  1049. mAddedToCount = true;
  1050. }
  1051. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  1052. /*if (mCompiler->mIsResolveOnly)
  1053. BF_ASSERT(mIsResolveOnly);*/
  1054. mBfIRBuilder = new BfIRBuilder(this);
  1055. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  1056. SetupIRBuilder(dbgVerifyCodeGen);
  1057. }
  1058. }
  1059. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1060. {
  1061. String name = "FORCELINKMOD_" + module->mModuleName;
  1062. if (outName != NULL)
  1063. *outName = name;
  1064. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1065. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1066. }
  1067. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1068. {
  1069. BP_ZONE("BfModule::StartNewRevision");
  1070. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1071. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1072. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1073. if (mCompiler->mCompileState == BfCompiler::CompileState_Cleanup)
  1074. {
  1075. // Cleaning up local methods may cause some necessary NewRevisions
  1076. force = true;
  1077. }
  1078. // Already on new revision?
  1079. if ((mRevision == mCompiler->mRevision) && (!force))
  1080. return;
  1081. mHadBuildError = false;
  1082. mHadBuildWarning = false;
  1083. mExtensionCount = 0;
  1084. mRevision = mCompiler->mRevision;
  1085. mRebuildIdx++;
  1086. ClearModuleData(!force);
  1087. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1088. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1089. {
  1090. mStringPoolRefs.Clear();
  1091. mUnreifiedStringPoolRefs.Clear();
  1092. }
  1093. mDllImportEntries.Clear();
  1094. mImportFileNames.Clear();
  1095. for (auto& pairVal : mDeferredMethodCallData)
  1096. delete pairVal.mValue;
  1097. mDeferredMethodCallData.Clear();
  1098. mDeferredMethodIds.Clear();
  1099. mModuleRefs.Clear();
  1100. mOutFileNames.Clear();
  1101. mTypeDataRefs.Clear();
  1102. mInterfaceSlotRefs.Clear();
  1103. if (rebuildKind == BfModule::RebuildKind_None)
  1104. {
  1105. for (auto& specPair : mSpecializedMethodModules)
  1106. {
  1107. auto specModule = specPair.mValue;
  1108. if (specModule->mIsReified != mIsReified)
  1109. {
  1110. if (mIsReified)
  1111. specModule->ReifyModule();
  1112. else
  1113. specModule->UnreifyModule();
  1114. }
  1115. }
  1116. }
  1117. else
  1118. {
  1119. for (auto& specPair : mSpecializedMethodModules)
  1120. {
  1121. auto specModule = specPair.mValue;
  1122. delete specModule;
  1123. }
  1124. }
  1125. mSpecializedMethodModules.Clear();
  1126. delete mNextAltModule;
  1127. mNextAltModule = NULL;
  1128. BF_ASSERT(mModuleOptions == NULL);
  1129. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1130. bool needsTypePopulated = false;
  1131. int oldOnDemandCount = 0;
  1132. // We don't have to rebuild types in the unspecialized module because there is no
  1133. // data that's needed -- their method instances are all NULL and the module
  1134. // doesn't get included in the build
  1135. if (this != mContext->mScratchModule)
  1136. {
  1137. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1138. {
  1139. auto typeInst = mOwnedTypeInstances[typeIdx];
  1140. if (!typeInst->IsDeleting())
  1141. {
  1142. typeInst->mIsReified = mIsReified;
  1143. if (rebuildKind != BfModule::RebuildKind_None)
  1144. {
  1145. if (typeInst->IsOnDemand())
  1146. {
  1147. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1148. if (rebuildKind == BfModule::RebuildKind_All)
  1149. mContext->DeleteType(typeInst);
  1150. else
  1151. {
  1152. RebuildMethods(typeInst);
  1153. }
  1154. }
  1155. else
  1156. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1157. mContext->RebuildType(typeInst, false, false, true);
  1158. //mContext->RebuildType(typeInst, false, false, false);
  1159. }
  1160. else
  1161. {
  1162. auto _HandleMethod = [&](BfMethodInstance* methodInstance)
  1163. {
  1164. if ((methodInstance != NULL) && (methodInstance->mDeclModule != NULL))
  1165. methodInstance->mDeclModule = this;
  1166. };
  1167. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1168. {
  1169. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1170. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  1171. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  1172. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  1173. {
  1174. oldOnDemandCount++;
  1175. }
  1176. _HandleMethod(methodGroup.mDefault);
  1177. if (methodGroup.mMethodSpecializationMap != NULL)
  1178. for (auto& kv : *methodGroup.mMethodSpecializationMap)
  1179. _HandleMethod(kv.mValue);
  1180. }
  1181. }
  1182. if (typeInst->IsDeleting())
  1183. typeIdx--;
  1184. }
  1185. }
  1186. }
  1187. if (!mIsDeleting)
  1188. Init();
  1189. mOnDemandMethodCount += oldOnDemandCount;
  1190. VerifyOnDemandMethods();
  1191. }
  1192. void BfModule::StartExtension()
  1193. {
  1194. BF_ASSERT(!mIsModuleMutable);
  1195. BfLogSysM("Extension started of module %p\n", this);
  1196. mExtensionCount++;
  1197. if (mBfIRBuilder != NULL)
  1198. mPrevIRBuilders.push_back(mBfIRBuilder);
  1199. mBfIRBuilder = NULL;
  1200. mWantsIRIgnoreWrites = false;
  1201. mFuncReferences.Clear();
  1202. mClassVDataRefs.Clear();
  1203. mClassVDataExtRefs.Clear();
  1204. for (auto& kv : mTypeDataRefs)
  1205. kv.mValue = BfIRValue();
  1206. mDbgRawAllocDataRefs.Clear();
  1207. mStringCharPtrPool.Clear();
  1208. mStringObjectPool.Clear();
  1209. mStaticFieldRefs.Clear();
  1210. for (auto& kv : mInterfaceSlotRefs)
  1211. kv.mValue = BfIRValue();
  1212. for (auto& pairVal : mDeferredMethodCallData)
  1213. delete pairVal.mValue;
  1214. mDeferredMethodCallData.Clear();
  1215. mDeferredMethodIds.Clear();
  1216. DisownMethods();
  1217. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1218. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1219. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1220. Init(false);
  1221. if (!wasAwaitingInitFinish)
  1222. FinishInit();
  1223. mOnDemandMethodCount = prevOnDemandMethodCount;
  1224. }
  1225. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1226. {
  1227. auto hasObjectDebugFlags = mContext->mBfObjectType->mFieldInstances[0].mResolvedType->IsInteger();
  1228. BfIRValue vDataValue;
  1229. if (hasObjectDebugFlags)
  1230. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1231. else
  1232. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1233. typeValueParams.push_back(vDataValue);
  1234. if (hasObjectDebugFlags)
  1235. {
  1236. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1237. typeValueParams.push_back(GetDefaultValue(primType));
  1238. }
  1239. }
  1240. BfIRValue BfModule::GetConstValue(int64 val)
  1241. {
  1242. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1243. }
  1244. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1245. {
  1246. BfType* checkType = type;
  1247. if (type->IsTypedPrimitive())
  1248. {
  1249. checkType = type->GetUnderlyingType();
  1250. }
  1251. if (checkType->IsPrimitiveType())
  1252. {
  1253. auto primType = (BfPrimitiveType*)checkType;
  1254. if (checkType->IsFloat())
  1255. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1256. else
  1257. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1258. }
  1259. return BfIRValue();
  1260. }
  1261. BfIRValue BfModule::GetConstValue8(int val)
  1262. {
  1263. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1264. }
  1265. BfIRValue BfModule::GetConstValue32(int32 val)
  1266. {
  1267. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1268. }
  1269. BfIRValue BfModule::GetConstValue64(int64 val)
  1270. {
  1271. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1272. }
  1273. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1274. {
  1275. PopulateType(type, BfPopulateType_Data);
  1276. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1277. if (type->IsTypedPrimitive())
  1278. {
  1279. auto underlyingType = type->GetUnderlyingType();
  1280. if (underlyingType == NULL)
  1281. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1282. return GetDefaultValue(type->GetUnderlyingType());
  1283. }
  1284. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1285. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1286. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1287. if ((type->IsIntegral()) || (type->IsBoolean()))
  1288. {
  1289. auto primType = (BfPrimitiveType*)type;
  1290. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1291. }
  1292. if (type->IsFloat())
  1293. {
  1294. auto primType = (BfPrimitiveType*)type;
  1295. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1296. }
  1297. return mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(type));
  1298. }
  1299. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1300. {
  1301. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1302. if (type->mSize == 0)
  1303. return BfTypedValue(BfIRValue::sValueless, type);
  1304. else
  1305. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1306. }
  1307. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1308. {
  1309. if (type->IsVar())
  1310. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1311. PopulateType(type, BfPopulateType_Data);
  1312. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1313. if (defaultValueKind == BfDefaultValueKind_Undef)
  1314. {
  1315. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(type)), type);
  1316. }
  1317. BfTypedValue typedValue;
  1318. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1319. {
  1320. if (type->IsRef())
  1321. {
  1322. BfRefType* refType = (BfRefType*)type;
  1323. BfType* underlyingType = refType->GetUnderlyingType();
  1324. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1325. }
  1326. else
  1327. {
  1328. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1329. }
  1330. if (!mBfIRBuilder->mIgnoreWrites)
  1331. {
  1332. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1333. GetConstValue(type->mSize), type->mAlign);
  1334. }
  1335. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1336. typedValue = LoadValue(typedValue);
  1337. return typedValue;
  1338. }
  1339. if ((type->IsRef()) && (!allowRef))
  1340. {
  1341. BfRefType* refType = (BfRefType*)type;
  1342. BfType* underlyingType = refType->GetUnderlyingType();
  1343. if (underlyingType->IsValuelessType())
  1344. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1345. else
  1346. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1347. }
  1348. else
  1349. {
  1350. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1351. }
  1352. return typedValue;
  1353. }
  1354. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1355. {
  1356. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1357. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1358. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1359. BfIRValue strConstant;
  1360. if (define)
  1361. {
  1362. strConstant = mBfIRBuilder->CreateConstString(str);
  1363. }
  1364. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1365. true, BfIRLinkageType_External,
  1366. strConstant, stringDataName);
  1367. if (define)
  1368. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1369. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1370. }
  1371. void BfModule::FixConstValueParams(BfTypeInstance* typeInst, SizedArrayImpl<BfIRValue>& valueParams, bool fillInPadding)
  1372. {
  1373. if ((!typeInst->mTypeDef->mIsCombinedPartial) && (!fillInPadding))
  1374. return;
  1375. int prevDataIdx = -1;
  1376. int usedDataIdx = 0;
  1377. int valueParamIdx = 0;
  1378. if (typeInst->mBaseType != NULL)
  1379. {
  1380. usedDataIdx++;
  1381. valueParamIdx++;
  1382. prevDataIdx++;
  1383. }
  1384. int startingParamsSize = (int)valueParams.mSize;
  1385. for (int fieldIdx = 0; fieldIdx < (int)typeInst->mFieldInstances.size(); fieldIdx++)
  1386. {
  1387. auto fieldInstance = &typeInst->mFieldInstances[fieldIdx];
  1388. if (fieldInstance->mDataIdx < 0)
  1389. continue;
  1390. BF_ASSERT(fieldInstance->mDataIdx > prevDataIdx);
  1391. if (fillInPadding)
  1392. {
  1393. for (int i = prevDataIdx + 1; i < fieldInstance->mDataIdx; i++)
  1394. valueParams.Insert(valueParamIdx++, mBfIRBuilder->CreateConstArrayZero(0));
  1395. }
  1396. valueParamIdx++;
  1397. prevDataIdx = fieldInstance->mDataIdx;
  1398. usedDataIdx++;
  1399. if (usedDataIdx <= valueParams.mSize)
  1400. continue;
  1401. valueParams.Add(GetDefaultValue(fieldInstance->mResolvedType));
  1402. }
  1403. }
  1404. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1405. {
  1406. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1407. mBfIRBuilder->PopulateType(stringTypeInst);
  1408. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1409. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1410. BfIRValue stringValData;
  1411. if (define)
  1412. {
  1413. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1414. mStringCharPtrPool[stringId] = stringCharsVal;
  1415. SizedArray<BfIRValue, 8> typeValueParams;
  1416. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1417. FixConstValueParams(stringTypeInst->mBaseType, typeValueParams);
  1418. auto objData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1419. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1420. typeValueParams.clear();
  1421. typeValueParams.push_back(objData);
  1422. if (lenByteCount == 4)
  1423. {
  1424. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1425. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1426. }
  1427. else
  1428. {
  1429. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1430. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1431. }
  1432. typeValueParams.push_back(stringCharsVal); // mPtr
  1433. FixConstValueParams(stringTypeInst, typeValueParams);
  1434. stringValData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1435. }
  1436. mBfIRBuilder->PopulateType(stringTypeInst);
  1437. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1438. mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full),
  1439. true,
  1440. BfIRLinkageType_External,
  1441. define ? stringValData : BfIRValue(),
  1442. stringObjName);
  1443. return stringValLiteral;
  1444. }
  1445. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1446. {
  1447. BF_ASSERT(constantStr.IsConst());
  1448. if (constHolder == NULL)
  1449. constHolder = mBfIRBuilder;
  1450. auto constant = constHolder->GetConstant(constantStr);
  1451. if (constant->mTypeCode == BfTypeCode_StringId)
  1452. {
  1453. return constant->mInt32;
  1454. }
  1455. while (constant->mConstType == BfConstType_BitCast)
  1456. {
  1457. auto constBitCast = (BfConstantBitCast*)constant;
  1458. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1459. }
  1460. if (constant->mConstType == BfConstType_GEP32_2)
  1461. {
  1462. auto constGEP = (BfConstantGEP32_2*)constant;
  1463. constant = constHolder->GetConstantById(constGEP->mTarget);
  1464. }
  1465. if (constant->mConstType == BfConstType_GlobalVar)
  1466. {
  1467. auto constGV = (BfGlobalVar*)constant;
  1468. const char* strDataPrefix = "__bfStrData";
  1469. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1470. return atoi(constGV->mName + strlen(strDataPrefix));
  1471. const char* strObjPrefix = "__bfStrObj";
  1472. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1473. return atoi(constGV->mName + strlen(strObjPrefix));
  1474. }
  1475. return -1;
  1476. }
  1477. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1478. {
  1479. int strId = GetStringPoolIdx(constantStr, constHolder);
  1480. if (strId != -1)
  1481. {
  1482. auto& entry = mContext->mStringObjectIdMap[strId];
  1483. return &entry.mString;
  1484. }
  1485. return NULL;
  1486. }
  1487. CeDbgState* BfModule::GetCeDbgState()
  1488. {
  1489. if (!mIsComptimeModule)
  1490. return NULL;
  1491. if ((mCompiler->mCeMachine != NULL) && (mCompiler->mCeMachine->mDebugger != NULL))
  1492. return mCompiler->mCeMachine->mDebugger->mCurDbgState;
  1493. return NULL;
  1494. }
  1495. BfIRValue BfModule::GetStringCharPtr(int stringId, bool force)
  1496. {
  1497. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1498. {
  1499. mUnreifiedStringPoolRefs.Add(stringId);
  1500. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, stringId);
  1501. }
  1502. BfIRValue* irValue = NULL;
  1503. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1504. return *irValue;
  1505. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1506. if (!mStringObjectPool.ContainsKey(stringId))
  1507. mStringPoolRefs.Add(stringId);
  1508. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1509. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1510. *irValue = strCharPtrConst;
  1511. return strCharPtrConst;
  1512. }
  1513. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue, bool force)
  1514. {
  1515. if (strValue.IsConst())
  1516. {
  1517. int stringId = GetStringPoolIdx(strValue);
  1518. BF_ASSERT(stringId != -1);
  1519. return GetStringCharPtr(stringId, force);
  1520. }
  1521. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1522. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1523. return charPtr;
  1524. }
  1525. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str, bool force)
  1526. {
  1527. return GetStringCharPtr(GetStringObjectValue(str, force), force);
  1528. }
  1529. BfIRValue BfModule::GetStringObjectValue(int strId, bool define, bool force)
  1530. {
  1531. BfIRValue* objValue;
  1532. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1533. return *objValue;
  1534. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1535. return GetStringObjectValue(stringPoolEntry.mString, define, force);
  1536. }
  1537. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define, bool force)
  1538. {
  1539. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1540. mBfIRBuilder->PopulateType(stringType);
  1541. int strId = mContext->GetStringLiteralId(str);
  1542. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1543. {
  1544. auto refModule = this;
  1545. if ((this == mContext->mUnreifiedModule) && (mCurTypeInstance != NULL))
  1546. refModule = mCurTypeInstance->mModule;
  1547. refModule->mUnreifiedStringPoolRefs.Add(strId);
  1548. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, strId);
  1549. }
  1550. BfIRValue* irValuePtr = NULL;
  1551. if (mStringObjectPool.TryGetValue(strId, &irValuePtr))
  1552. return *irValuePtr;
  1553. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1554. if (!mStringCharPtrPool.ContainsKey(strId))
  1555. mStringPoolRefs.Add(strId);
  1556. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1557. mStringObjectPool[strId] = strObject;
  1558. mStringPoolRefs.Add(strId);
  1559. return strObject;
  1560. }
  1561. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1562. {
  1563. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1564. type,
  1565. true,
  1566. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1567. constant,
  1568. name.c_str());
  1569. return newConst;
  1570. }
  1571. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1572. {
  1573. auto curScope = mCurMethodState->mCurScope;
  1574. if (curScope->mLabelNode != NULL)
  1575. {
  1576. curScope->mLabelNode->ToString(curScope->mLabel);
  1577. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1578. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1579. auto autoComplete = mCompiler->GetAutoComplete();
  1580. if (autoComplete != NULL)
  1581. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1582. }
  1583. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1584. {
  1585. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1586. while (checkScope != NULL)
  1587. {
  1588. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1589. {
  1590. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1591. if (errorNode != NULL)
  1592. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1593. break;
  1594. }
  1595. checkScope = checkScope->mPrevScope;
  1596. }
  1597. }
  1598. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1599. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1600. {
  1601. if (prevScope->mHadScopeValueRetain)
  1602. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1603. else
  1604. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1605. }
  1606. mCurMethodState->mBlockNestLevel++;
  1607. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1608. {
  1609. // DIScope could be NULL if we're in an unspecialized method (for example)
  1610. if (mCurMethodState->mCurScope->mDIScope)
  1611. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1612. }
  1613. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1614. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1615. mCurMethodState->mCurScope->mMixinState = mCurMethodState->mMixinState;
  1616. }
  1617. void BfModule::RestoreScoreState_LocalVariables()
  1618. {
  1619. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1620. {
  1621. auto localVar = mCurMethodState->mLocals.back();
  1622. LocalVariableDone(localVar, false);
  1623. mCurMethodState->mLocals.pop_back();
  1624. if (localVar->mShadowedLocal != NULL)
  1625. {
  1626. BfLocalVarEntry* localVarEntryPtr;
  1627. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1628. {
  1629. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1630. }
  1631. }
  1632. else
  1633. {
  1634. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1635. }
  1636. delete localVar;
  1637. }
  1638. }
  1639. void BfModule::RestoreScopeState()
  1640. {
  1641. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1642. mCurMethodState->mBlockNestLevel--;
  1643. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1644. {
  1645. BfIRBlock afterEndBlock;
  1646. if (!mCurMethodState->mLeftBlockUncond)
  1647. {
  1648. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1649. mBfIRBuilder->CreateBr(afterEndBlock);
  1650. mBfIRBuilder->ClearDebugLocation_Last();
  1651. }
  1652. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1653. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1654. if (afterEndBlock)
  1655. {
  1656. mBfIRBuilder->AddBlock(afterEndBlock);
  1657. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1658. }
  1659. }
  1660. if (!mCurMethodState->mLeftBlockUncond)
  1661. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1662. RestoreScoreState_LocalVariables();
  1663. if (mCurMethodState->mCurScope->mValueScopeStart)
  1664. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1665. mCurMethodState->mCurScope = prevScopeData;
  1666. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1667. }
  1668. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1669. {
  1670. if (mBfIRBuilder->mIgnoreWrites)
  1671. return mBfIRBuilder->GetFakeVal();
  1672. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1673. mBfIRBuilder->PopulateType(type);
  1674. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1675. if (!mBfIRBuilder->mIgnoreWrites)
  1676. BF_ASSERT(!prevInsertBlock.IsFake());
  1677. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1678. BfIRValue allocaInst;
  1679. if (arraySize)
  1680. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1681. else
  1682. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1683. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1684. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1685. if (name != NULL)
  1686. mBfIRBuilder->SetName(allocaInst, name);
  1687. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1688. if ((addLifetime) && (WantsLifetimes()))
  1689. {
  1690. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1691. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1692. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1693. }
  1694. return allocaInst;
  1695. }
  1696. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1697. {
  1698. if (mBfIRBuilder->mIgnoreWrites)
  1699. return mBfIRBuilder->GetFakeVal();
  1700. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1701. mBfIRBuilder->PopulateType(typeInst);
  1702. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1703. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1704. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1705. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1706. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1707. if (name != NULL)
  1708. mBfIRBuilder->SetName(allocaInst, name);
  1709. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1710. if ((addLifetime) && (WantsLifetimes()))
  1711. {
  1712. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1713. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1714. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1715. }
  1716. return allocaInst;
  1717. }
  1718. BfDeferredCallEntry* BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape, BfIRBlock valBlock)
  1719. {
  1720. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1721. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1722. /*if (mCurMethodState->mInHeadScope)
  1723. isScopeAlloc = true;*/
  1724. if (scopeData == NULL)
  1725. return NULL;
  1726. auto checkBaseType = val.mType->ToTypeInstance();
  1727. if ((checkBaseType != NULL) && (checkBaseType->IsObject()) && (!arraySize))
  1728. {
  1729. bool hadDtorCall = false;
  1730. while (checkBaseType != NULL)
  1731. {
  1732. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  1733. if (dtorMethodDef != NULL)
  1734. {
  1735. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  1736. if (dtorMethodInstance)
  1737. {
  1738. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1739. BfIRValue useVal = val.mValue;
  1740. BfIRBlock prevBlock = mBfIRBuilder->GetInsertBlock();
  1741. if (valBlock)
  1742. mBfIRBuilder->SetInsertPoint(valBlock);
  1743. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1744. if (!useVal.IsConst())
  1745. mBfIRBuilder->ClearDebugLocation(useVal);
  1746. if (valBlock)
  1747. mBfIRBuilder->SetInsertPoint(prevBlock);
  1748. if (isDynAlloc)
  1749. {
  1750. //
  1751. }
  1752. else if (condAlloca)
  1753. {
  1754. BF_ASSERT(!IsTargetingBeefBackend());
  1755. BF_ASSERT(!isDynAlloc);
  1756. auto valPtr = CreateAlloca(checkBaseType);
  1757. mBfIRBuilder->ClearDebugLocation_Last();
  1758. mBfIRBuilder->CreateStore(useVal, valPtr);
  1759. mBfIRBuilder->ClearDebugLocation_Last();
  1760. useVal = valPtr;
  1761. }
  1762. SizedArray<BfIRValue, 1> llvmArgs;
  1763. llvmArgs.push_back(useVal);
  1764. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1765. if (deferredCall != NULL)
  1766. {
  1767. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1768. if (condAlloca)
  1769. deferredCall->mArgsNeedLoad = true;
  1770. }
  1771. hadDtorCall = true;
  1772. break;
  1773. }
  1774. }
  1775. checkBaseType = checkBaseType->mBaseType;
  1776. }
  1777. return NULL;
  1778. }
  1779. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1780. if (mayEscape)
  1781. {
  1782. if ((!IsOptimized()) && (!mIsComptimeModule) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1783. {
  1784. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1785. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1786. if (!isDyn)
  1787. {
  1788. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1789. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1790. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1791. if (!dtorMethodInstance.mMethodInstance)
  1792. {
  1793. Fail(StrFormat("Unable to find %s", methodName));
  1794. }
  1795. else
  1796. {
  1797. SizedArray<BfIRValue, 1> llvmArgs;
  1798. if (IsTargetingBeefBackend())
  1799. {
  1800. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1801. //mBfIRBuilder->ClearDebugLocation_Last();
  1802. }
  1803. else
  1804. llvmArgs.push_back(val.mValue);
  1805. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1806. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1807. if (arraySize)
  1808. llvmArgs.push_back(arraySize);
  1809. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1810. }
  1811. }
  1812. else
  1813. {
  1814. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1815. {
  1816. BfIRValue clearSize = arraySize;
  1817. if (val.mType->GetStride() > 1)
  1818. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1819. const char* methodName = "SetDeletedX";
  1820. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1821. BF_ASSERT(dtorMethodInstance);
  1822. if (!dtorMethodInstance)
  1823. {
  1824. Fail(StrFormat("Unable to find %s", methodName));
  1825. }
  1826. else
  1827. {
  1828. SizedArray<BfIRValue, 1> llvmArgs;
  1829. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1830. //mBfIRBuilder->ClearDebugLocation_Last();
  1831. llvmArgs.push_back(clearSize);
  1832. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1833. }
  1834. }
  1835. else
  1836. {
  1837. intptr clearSize = val.mType->mSize;
  1838. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1839. if (constant != NULL)
  1840. clearSize = (intptr)(clearSize * constant->mInt64);
  1841. const char* funcName = "SetDeleted1";
  1842. if (clearSize >= 16)
  1843. funcName = "SetDeleted16";
  1844. else if (clearSize >= 8)
  1845. funcName = "SetDeleted8";
  1846. else if (clearSize >= 4)
  1847. funcName = "SetDeleted4";
  1848. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1849. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1850. if (!dtorMethodInstance)
  1851. {
  1852. Fail(StrFormat("Unable to find %s", funcName));
  1853. }
  1854. else
  1855. {
  1856. SizedArray<BfIRValue, 1> llvmArgs;
  1857. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1858. //mBfIRBuilder->ClearDebugLocation_Last();
  1859. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1860. }
  1861. }
  1862. }
  1863. }
  1864. }
  1865. return NULL;
  1866. }
  1867. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1868. {
  1869. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1870. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1871. return false;
  1872. auto checkTypeInstance = startTypeInstance;
  1873. while (checkTypeInstance != NULL)
  1874. {
  1875. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1876. {
  1877. if (fieldInstance.mMergedDataIdx != -1)
  1878. {
  1879. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1880. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1881. {
  1882. // For fields added in extensions, we automatically initialize those if necessary
  1883. auto fieldDef = fieldInstance.GetFieldDef();
  1884. if (!fieldDef->mDeclaringType->IsExtension())
  1885. return false;
  1886. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  1887. {
  1888. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1889. mBfIRBuilder->SaveDebugLocation();
  1890. if (localVar->IsParam())
  1891. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1892. else
  1893. {
  1894. BF_ASSERT(localVar->mDeclBlock);
  1895. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1896. }
  1897. mBfIRBuilder->ClearDebugLocation();
  1898. BfIRValue curVal;
  1899. if (localVar->mIsThis)
  1900. curVal = mBfIRBuilder->GetArgument(0);
  1901. else
  1902. curVal = localVar->mAddr;
  1903. auto subTypeInstance = startTypeInstance;
  1904. while (subTypeInstance != checkTypeInstance)
  1905. {
  1906. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1907. subTypeInstance = subTypeInstance->mBaseType;
  1908. }
  1909. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1910. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1911. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1912. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1913. mBfIRBuilder->RestoreDebugLocation();
  1914. }
  1915. localVar->mUnassignedFieldFlags &= ~checkMask;
  1916. if (localVar->mUnassignedFieldFlags == 0)
  1917. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1918. }
  1919. }
  1920. }
  1921. checkTypeInstance = checkTypeInstance->mBaseType;
  1922. }
  1923. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  1924. }
  1925. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1926. {
  1927. BfAstNode* localNameNode = localVar->mNameNode;
  1928. if (localVar->mIsThis)
  1929. {
  1930. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1931. }
  1932. if (localNameNode != NULL)
  1933. {
  1934. bool isOut = false;
  1935. if (localVar->mResolvedType->IsRef())
  1936. {
  1937. auto refType = (BfRefType*)localVar->mResolvedType;
  1938. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1939. }
  1940. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1941. {
  1942. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  1943. TryLocalVariableInit(localVar);
  1944. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1945. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1946. // We may have init blocks that we aren't processing here...
  1947. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  1948. deferFullAnalysis = true;
  1949. //bool deferFullAnalysis = true;
  1950. bool deferUsageWarning = deferFullAnalysis && (mCompiler->IsAutocomplete()) &&
  1951. (mCompiler->mResolvePassData->mAutoComplete->mResolveType != BfResolveType_GetFixits);
  1952. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  1953. (!localVar->mIsImplicitParam))
  1954. {
  1955. if (deferUsageWarning)
  1956. {
  1957. // Ignore
  1958. }
  1959. else if (localVar->mIsThis)
  1960. {
  1961. bool foundFields = false;
  1962. auto checkTypeInstance = mCurTypeInstance;
  1963. while (checkTypeInstance != NULL)
  1964. {
  1965. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1966. {
  1967. if (fieldInstance.mMergedDataIdx == -1)
  1968. continue;
  1969. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1970. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1971. {
  1972. auto fieldDef = fieldInstance.GetFieldDef();
  1973. if (mCurMethodInstance->mMethodDef->mDeclaringType->mIsPartial)
  1974. {
  1975. if (mCurMethodInstance->mMethodDef->mDeclaringType != fieldInstance.GetFieldDef()->mDeclaringType)
  1976. {
  1977. // This extension is only responsible for its own fields
  1978. foundFields = true;
  1979. continue;
  1980. }
  1981. if ((fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mInitializer != NULL))
  1982. {
  1983. // This initializer was handled in CtorNoBody
  1984. foundFields = true;
  1985. continue;
  1986. }
  1987. }
  1988. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  1989. {
  1990. String propName;
  1991. if (propertyDeclaration->mNameNode != NULL)
  1992. propertyDeclaration->mNameNode->ToString(propName);
  1993. if (checkTypeInstance == mCurTypeInstance)
  1994. {
  1995. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  1996. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1997. }
  1998. else
  1999. {
  2000. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  2001. TypeToString(checkTypeInstance).c_str(),
  2002. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2003. }
  2004. }
  2005. else
  2006. {
  2007. if (checkTypeInstance == mCurTypeInstance)
  2008. {
  2009. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  2010. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2011. }
  2012. else
  2013. {
  2014. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  2015. TypeToString(checkTypeInstance).c_str(),
  2016. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2017. }
  2018. }
  2019. foundFields = true;
  2020. }
  2021. }
  2022. checkTypeInstance = checkTypeInstance->mBaseType;
  2023. }
  2024. if (!foundFields)
  2025. {
  2026. if (mCurTypeInstance->mInstSize > 0)
  2027. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  2028. }
  2029. }
  2030. else if (localVar->IsParam())
  2031. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  2032. else if (!deferUsageWarning)
  2033. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2034. }
  2035. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  2036. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2037. }
  2038. }
  2039. }
  2040. void BfModule::CreateRetValLocal()
  2041. {
  2042. if (mCurMethodState->mRetVal)
  2043. {
  2044. BfLocalVariable* localDef = new BfLocalVariable();
  2045. localDef->mName = "return";
  2046. localDef->mResolvedType = mCurMethodState->mRetVal.mType;
  2047. localDef->mAddr = mCurMethodState->mRetVal.mValue;
  2048. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2049. AddLocalVariableDef(localDef);
  2050. }
  2051. else if (mCurMethodState->mRetValAddr)
  2052. {
  2053. BfLocalVariable* localDef = new BfLocalVariable();
  2054. localDef->mName = "return";
  2055. localDef->mResolvedType = CreateRefType(mCurMethodInstance->mReturnType);
  2056. localDef->mAddr = mCurMethodState->mRetValAddr;
  2057. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2058. AddLocalVariableDef(localDef);
  2059. }
  2060. }
  2061. void BfModule::MarkDynStack(BfScopeData* scopeData)
  2062. {
  2063. auto checkScope = mCurMethodState->mCurScope;
  2064. while (true)
  2065. {
  2066. if (checkScope == scopeData)
  2067. break;
  2068. checkScope->mHadOuterDynStack = true;
  2069. checkScope = checkScope->mPrevScope;
  2070. }
  2071. }
  2072. void BfModule::SaveStackState(BfScopeData* scopeData)
  2073. {
  2074. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  2075. // scopes within scopeData restore the stack
  2076. auto checkScope = mCurMethodState->mCurScope;
  2077. while (true)
  2078. {
  2079. if (checkScope == scopeData)
  2080. {
  2081. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  2082. {
  2083. if (mBfIRBuilder->mHasDebugInfo)
  2084. mBfIRBuilder->SaveDebugLocation();
  2085. auto prevPos = mBfIRBuilder->GetInsertBlock();
  2086. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  2087. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  2088. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  2089. mBfIRBuilder->SetInsertPoint(prevPos);
  2090. if (mBfIRBuilder->mHasDebugInfo)
  2091. mBfIRBuilder->RestoreDebugLocation();
  2092. }
  2093. break;
  2094. }
  2095. if (checkScope->mSavedStack)
  2096. {
  2097. for (auto usage : checkScope->mSavedStackUses)
  2098. mBfIRBuilder->EraseInstFromParent(usage);
  2099. checkScope->mSavedStackUses.Clear();
  2100. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  2101. checkScope->mSavedStack = BfIRValue();
  2102. }
  2103. checkScope = checkScope->mPrevScope;
  2104. }
  2105. }
  2106. BfIRValue BfModule::ValueScopeStart()
  2107. {
  2108. if (IsTargetingBeefBackend())
  2109. return mBfIRBuilder->CreateValueScopeStart();
  2110. return BfIRValue();
  2111. }
  2112. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  2113. {
  2114. if (valueScopeStart)
  2115. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  2116. }
  2117. BfProjectSet* BfModule::GetVisibleProjectSet()
  2118. {
  2119. if (mCurMethodState == NULL)
  2120. return NULL;
  2121. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  2122. {
  2123. HashSet<BfType*> seenTypes;
  2124. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  2125. {
  2126. if (mCurMethodState->mVisibleProjectSet.Add(project))
  2127. {
  2128. for (auto dep : project->mDependencies)
  2129. _AddProject(dep);
  2130. }
  2131. };
  2132. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  2133. {
  2134. auto typeInstance = type->ToTypeInstance();
  2135. if (typeInstance == NULL)
  2136. {
  2137. if (type->IsSizedArray())
  2138. _AddType(type->GetUnderlyingType());
  2139. return;
  2140. }
  2141. if (typeInstance->IsTuple())
  2142. {
  2143. for (auto& fieldInst : typeInstance->mFieldInstances)
  2144. {
  2145. if (fieldInst.mDataIdx != -1)
  2146. _AddType(fieldInst.mResolvedType);
  2147. }
  2148. }
  2149. _AddProject(typeInstance->mTypeDef->mProject);
  2150. if (typeInstance->mGenericTypeInfo == NULL)
  2151. return;
  2152. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2153. {
  2154. if (seenTypes.Add(type))
  2155. _AddType(type);
  2156. }
  2157. };
  2158. if (mCurTypeInstance != NULL)
  2159. _AddType(mCurTypeInstance);
  2160. auto methodState = mCurMethodState;
  2161. while (methodState != NULL)
  2162. {
  2163. if (methodState->mMethodInstance != NULL)
  2164. {
  2165. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  2166. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  2167. {
  2168. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2169. _AddType(type);
  2170. }
  2171. }
  2172. methodState = methodState->mPrevMethodState;
  2173. }
  2174. }
  2175. return &mCurMethodState->mVisibleProjectSet;
  2176. }
  2177. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2178. {
  2179. auto bfParser = astNode->GetSourceData()->ToParserData();
  2180. if (bfParser == NULL)
  2181. return NULL;
  2182. BfFileInstance** fileInstancePtr = NULL;
  2183. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2184. {
  2185. return *fileInstancePtr;
  2186. }
  2187. else
  2188. {
  2189. // It's possible two parsers have the same file name (ie: mNextRevision)
  2190. BfFileInstance** namedFileInstancePtr = NULL;
  2191. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2192. {
  2193. auto bfFileInstance = *namedFileInstancePtr;
  2194. *fileInstancePtr = bfFileInstance;
  2195. return bfFileInstance;
  2196. }
  2197. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2198. auto bfFileInstance = new BfFileInstance();
  2199. *fileInstancePtr = bfFileInstance;
  2200. *namedFileInstancePtr = bfFileInstance;
  2201. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2202. bfFileInstance->mParser = bfParser;
  2203. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2204. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasLineInfo()))
  2205. {
  2206. String fileName = bfParser->mFileName;
  2207. for (int i = 0; i < (int)fileName.length(); i++)
  2208. {
  2209. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2210. fileName[i] = DIR_SEP_CHAR;
  2211. }
  2212. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, BF_MAX(slashPos, 0)), bfParser->mMD5Hash);
  2213. }
  2214. return bfFileInstance;
  2215. }
  2216. }
  2217. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2218. {
  2219. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2220. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2221. return;
  2222. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2223. if (astNode == NULL)
  2224. return;
  2225. auto bfParser = astNode->GetSourceData()->ToParserData();
  2226. if (bfParser == NULL)
  2227. return;
  2228. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2229. {
  2230. if (mCurFilePosition.mFileInstance != NULL)
  2231. {
  2232. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2233. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2234. }
  2235. auto bfFileInstance = GetFileFromNode(astNode);
  2236. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2237. {
  2238. mCurFilePosition = bfFileInstance->mPrevPosition;
  2239. }
  2240. else
  2241. {
  2242. mCurFilePosition.mFileInstance = bfFileInstance;
  2243. mCurFilePosition.mCurLine = 0;
  2244. mCurFilePosition.mCurSrcPos = 0;
  2245. }
  2246. }
  2247. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2248. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2249. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2250. if (jumpEntry->mCharIdx > srcPos)
  2251. jumpEntry--;
  2252. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2253. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2254. mCurFilePosition.mCurColumn = 0;
  2255. while (mCurFilePosition.mCurSrcPos < srcPos)
  2256. {
  2257. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2258. {
  2259. mCurFilePosition.mCurLine++;
  2260. mCurFilePosition.mCurColumn = 0;
  2261. }
  2262. else
  2263. {
  2264. mCurFilePosition.mCurColumn++;
  2265. }
  2266. mCurFilePosition.mCurSrcPos++;
  2267. }
  2268. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2269. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasLineInfo()) && (mCurMethodState != NULL))
  2270. {
  2271. int column = mCurFilePosition.mCurColumn + 1;
  2272. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2273. {
  2274. // Set to illegal position
  2275. column = 0;
  2276. }
  2277. if (mSetIllegalSrcPosition)
  2278. column = 0;
  2279. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2280. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2281. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2282. {
  2283. // This is from a different scope...
  2284. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2285. {
  2286. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2287. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2288. }
  2289. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2290. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2291. }
  2292. else
  2293. {
  2294. if (mCurMethodState->mCurScope->mAltDIFile)
  2295. {
  2296. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2297. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2298. }
  2299. }
  2300. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2301. if (mCurMethodState->mCrossingMixin)
  2302. inlineAt = BfIRMDNode();
  2303. if ((!useDIScope) && (mIsComptimeModule))
  2304. useDIScope = wantDIFile;
  2305. if (!useDIScope)
  2306. mBfIRBuilder->ClearDebugLocation();
  2307. else
  2308. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2309. if ((flags & BfSrcPosFlag_Expression) == 0)
  2310. mBfIRBuilder->CreateStatementStart();
  2311. }
  2312. }
  2313. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2314. {
  2315. // We've turned off expr src pos (for now?)
  2316. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2317. }
  2318. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2319. {
  2320. if (mCompiler->mBfObjectTypeDef != NULL)
  2321. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2322. SetIllegalSrcPos();
  2323. }
  2324. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2325. {
  2326. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2327. {
  2328. auto curScope = mCurMethodState->mCurScope->mDIScope;
  2329. if (curScope)
  2330. {
  2331. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2332. {
  2333. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2334. mBfIRBuilder->SetCurrentDebugLocation(0, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2335. }
  2336. else
  2337. {
  2338. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2339. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2340. }
  2341. }
  2342. if ((flags & BfSrcPosFlag_Expression) == 0)
  2343. mBfIRBuilder->CreateStatementStart();
  2344. }
  2345. }
  2346. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2347. {
  2348. // We've turned off expr src pos (for now?)
  2349. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2350. }
  2351. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2352. {
  2353. if ((protection == BfProtection_Public) ||
  2354. (((protection == BfProtection_Protected) || (protection == BfProtection_ProtectedInternal)) && (allowProtected)) ||
  2355. ((protection == BfProtection_Private) && (allowPrivate)))
  2356. return true;
  2357. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2358. {
  2359. mAttributeState->mUsed = true;
  2360. return true;
  2361. }
  2362. if (((protection == BfProtection_Internal) || (protection == BfProtection_ProtectedInternal)) && (checkType != NULL))
  2363. {
  2364. if (CheckInternalProtection(checkType))
  2365. return true;
  2366. }
  2367. return false;
  2368. }
  2369. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2370. {
  2371. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2372. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2373. {
  2374. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2375. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2376. }
  2377. allowProtected = allowPrivate;
  2378. }
  2379. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2380. {
  2381. if (memberProtection == BfProtection_Hidden)
  2382. return false;
  2383. if (memberProtection == BfProtection_Public)
  2384. return true;
  2385. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2386. {
  2387. BfTypeInstance* curCheckType = mCurTypeInstance;
  2388. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2389. {
  2390. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2391. curCheckType = mixinOwner;
  2392. }
  2393. bool allowPrivate = (curCheckType != NULL) && (memberOwner->IsInstanceOf(curCheckType->mTypeDef));
  2394. if (curCheckType != NULL)
  2395. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2396. if (allowPrivate)
  2397. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2398. else
  2399. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2400. }
  2401. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2402. return true;
  2403. if ((memberProtection == BfProtection_Protected) || (memberProtection == BfProtection_ProtectedInternal))
  2404. {
  2405. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2406. {
  2407. bool allowProtected = false;
  2408. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2409. auto curCheckType = mCurTypeInstance;
  2410. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2411. {
  2412. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2413. curCheckType = mixinOwner;
  2414. }
  2415. if ((flags & BfProtectionCheckFlag_InstanceLookup) != 0)
  2416. {
  2417. auto lookupCheckType = lookupStartType;
  2418. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2419. {
  2420. if (lookupCheckType == curCheckType)
  2421. {
  2422. allowProtected = true;
  2423. break;
  2424. }
  2425. if (lookupCheckType == memberOwner)
  2426. break;
  2427. lookupCheckType = lookupCheckType->mBaseType;
  2428. if (lookupCheckType == NULL)
  2429. break;
  2430. }
  2431. }
  2432. else
  2433. {
  2434. auto lookupCheckType = curCheckType;
  2435. while (lookupCheckType->mInheritDepth >= memberOwner->mInheritDepth)
  2436. {
  2437. if (lookupCheckType == memberOwner)
  2438. {
  2439. allowProtected = true;
  2440. break;
  2441. }
  2442. lookupCheckType = lookupCheckType->mBaseType;
  2443. if (lookupCheckType == NULL)
  2444. break;
  2445. }
  2446. }
  2447. if (!allowProtected)
  2448. {
  2449. // It's possible our outer type is derived from 'memberOwner'
  2450. while (curCheckType->mTypeDef->mNestDepth > 0)
  2451. {
  2452. curCheckType = GetOuterType(curCheckType);
  2453. if (curCheckType == NULL)
  2454. break;
  2455. auto lookupCheckType = lookupStartType;
  2456. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2457. {
  2458. if (lookupCheckType == curCheckType)
  2459. {
  2460. allowProtected = true;
  2461. break;
  2462. }
  2463. if (lookupCheckType == memberOwner)
  2464. break;
  2465. lookupCheckType = lookupCheckType->mBaseType;
  2466. if (lookupCheckType == NULL)
  2467. break;
  2468. }
  2469. }
  2470. }
  2471. if (allowProtected)
  2472. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2473. else
  2474. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2475. }
  2476. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2477. return true;
  2478. }
  2479. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2480. {
  2481. mAttributeState->mUsed = true;
  2482. return true;
  2483. }
  2484. if (((memberProtection == BfProtection_Internal) || (memberProtection == BfProtection_ProtectedInternal)) && (memberOwner != NULL))
  2485. {
  2486. if (CheckInternalProtection(memberOwner->mTypeDef))
  2487. return true;
  2488. }
  2489. return false;
  2490. }
  2491. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2492. {
  2493. if (mCompiler->mResolvePassData != NULL)
  2494. {
  2495. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2496. sourceClassifier->SetElementType(astNode, elementType);
  2497. }
  2498. }
  2499. bool BfModule::PreFail()
  2500. {
  2501. if (!mIgnoreErrors)
  2502. return true;
  2503. SetFail();
  2504. return false;
  2505. }
  2506. void BfModule::SetFail()
  2507. {
  2508. if (mIgnoreErrors)
  2509. {
  2510. if (mAttributeState != NULL)
  2511. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2512. }
  2513. }
  2514. void BfModule::VerifyOnDemandMethods()
  2515. {
  2516. #ifdef _DEBUG
  2517. // if (mParentModule != NULL)
  2518. // {
  2519. // BF_ASSERT(mOnDemandMethodCount == 0);
  2520. // mParentModule->VerifyOnDemandMethods();
  2521. // return;
  2522. // }
  2523. //
  2524. // int onDemandCount = 0;
  2525. // for (auto type : mOwnedTypeInstances)
  2526. // {
  2527. // auto typeInst = type->ToTypeInstance();
  2528. // for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  2529. // {
  2530. // if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  2531. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  2532. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  2533. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  2534. // onDemandCount++;
  2535. // }
  2536. // }
  2537. //
  2538. // BF_ASSERT(mOnDemandMethodCount == onDemandCount);
  2539. #endif
  2540. }
  2541. bool BfModule::IsSkippingExtraResolveChecks()
  2542. {
  2543. if (mIsComptimeModule)
  2544. return false;
  2545. return mCompiler->IsSkippingExtraResolveChecks();
  2546. }
  2547. bool BfModule::AddErrorContext(StringImpl& errorString, BfAstNode* refNode, bool& isWhileSpecializing, bool isWarning)
  2548. {
  2549. bool isWhileSpecializingMethod = false;
  2550. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2551. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2552. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2553. errorString += StrFormat("\n while generating append size calculating method");
  2554. else if (refNode == NULL)
  2555. {
  2556. if (mCurTypeInstance != NULL)
  2557. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2558. else if (mProject != NULL)
  2559. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2560. }
  2561. if (mCurTypeInstance != NULL)
  2562. {
  2563. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2564. {
  2565. // Propogate the fail all the way to the main method (assuming we're in a local method or lambda)
  2566. if (isWarning)
  2567. methodInstance->mHasWarning = true;
  2568. else
  2569. methodInstance->mHasFailed = true;
  2570. if (!methodInstance->mHasStartedDeclaration)
  2571. StartMethodDeclaration(methodInstance, NULL);
  2572. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2573. if (isSpecializedMethod)
  2574. {
  2575. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2576. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2577. if (unspecializedMethod == methodInstance)
  2578. {
  2579. // This is a local method inside a generic method
  2580. BF_ASSERT(methodInstance->mMethodDef->mIsLocalMethod);
  2581. }
  2582. else
  2583. {
  2584. if (isWarning)
  2585. {
  2586. if (unspecializedMethod->mHasWarning)
  2587. return false; // At least SOME error has already been reported
  2588. }
  2589. else
  2590. {
  2591. if (unspecializedMethod->mHasFailed)
  2592. return false; // At least SOME error has already been reported
  2593. }
  2594. }
  2595. }
  2596. if (isSpecializedMethod)
  2597. {
  2598. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2599. isWhileSpecializing = true;
  2600. isWhileSpecializingMethod = true;
  2601. }
  2602. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2603. {
  2604. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2605. isWhileSpecializing = true;
  2606. isWhileSpecializingMethod = true;
  2607. }
  2608. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2609. {
  2610. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2611. isWhileSpecializing = true;
  2612. }
  2613. return true;
  2614. };
  2615. bool hadMethodInstance = false;
  2616. if (mCurMethodState != NULL)
  2617. {
  2618. auto checkMethodState = mCurMethodState;
  2619. while (checkMethodState != NULL)
  2620. {
  2621. auto methodInstance = checkMethodState->mMethodInstance;
  2622. if (methodInstance == NULL)
  2623. {
  2624. checkMethodState = checkMethodState->mPrevMethodState;
  2625. continue;
  2626. }
  2627. hadMethodInstance = true;
  2628. if (!_CheckMethodInstance(methodInstance))
  2629. return false;
  2630. checkMethodState = checkMethodState->mPrevMethodState;
  2631. }
  2632. }
  2633. if ((!hadMethodInstance) && (mCurMethodInstance != NULL))
  2634. {
  2635. if (!_CheckMethodInstance(mCurMethodInstance))
  2636. return false;
  2637. }
  2638. }
  2639. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2640. {
  2641. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2642. isWhileSpecializing = true;
  2643. }
  2644. return true;
  2645. }
  2646. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent, bool deferError)
  2647. {
  2648. BP_ZONE("BfModule::Fail");
  2649. if (mIgnoreErrors)
  2650. {
  2651. mHadIgnoredError = true;
  2652. if (mAttributeState != NULL)
  2653. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2654. return NULL;
  2655. }
  2656. if (!mReportErrors)
  2657. {
  2658. mCompiler->mPassInstance->SilentFail();
  2659. return NULL;
  2660. }
  2661. if (refNode != NULL)
  2662. refNode = BfNodeToNonTemporary(refNode);
  2663. //BF_ASSERT(refNode != NULL);
  2664. if (mIsComptimeModule)
  2665. {
  2666. if (auto ceDbgState = GetCeDbgState())
  2667. {
  2668. // Follow normal fail path
  2669. }
  2670. else
  2671. {
  2672. mHadBuildError = true;
  2673. if ((mCompiler->mCeMachine->mCurContext != NULL) && (mCompiler->mCeMachine->mCurContext->mCurCallSource != NULL) &&
  2674. (mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode != NULL))
  2675. {
  2676. BfError* bfError = mCompiler->mPassInstance->Fail("Comptime method generation had errors",
  2677. mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode);
  2678. if (bfError != NULL)
  2679. mCompiler->mPassInstance->MoreInfo(error, refNode);
  2680. return bfError;
  2681. }
  2682. return NULL;
  2683. }
  2684. }
  2685. if (mCurMethodInstance != NULL)
  2686. mCurMethodInstance->mHasFailed = true;
  2687. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2688. return NULL;
  2689. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2690. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2691. if (!mHadBuildError)
  2692. mHadBuildError = true;
  2693. if (mParentModule != NULL)
  2694. mParentModule->mHadBuildError = true;
  2695. if (mCurTypeInstance != NULL)
  2696. AddFailType(mCurTypeInstance);
  2697. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2698. String errorString = error;
  2699. bool isWhileSpecializing = false;
  2700. if (!AddErrorContext(errorString, refNode, isWhileSpecializing, false))
  2701. return NULL;
  2702. BfError* bfError = NULL;
  2703. if (isWhileSpecializing)
  2704. deferError = true;
  2705. if (!mHadBuildError)
  2706. mHadBuildError = true;
  2707. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2708. {
  2709. bfError = mCompiler->mPassInstance->Fail("Emitted code had errors", mCurMethodState->mEmitRefNode);
  2710. if (bfError != NULL)
  2711. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2712. return bfError;
  2713. }
  2714. // Check mixins
  2715. {
  2716. auto checkMethodState = mCurMethodState;
  2717. while (checkMethodState != NULL)
  2718. {
  2719. auto rootMixinState = checkMethodState->GetRootMixinState();
  2720. if (rootMixinState != NULL)
  2721. {
  2722. String mixinErr = StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str());
  2723. if (deferError)
  2724. bfError = mCompiler->mPassInstance->DeferFail(mixinErr, rootMixinState->mSource);
  2725. else
  2726. bfError = mCompiler->mPassInstance->Fail(mixinErr, rootMixinState->mSource);
  2727. if (bfError == NULL)
  2728. return NULL;
  2729. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2730. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2731. auto mixinState = checkMethodState->mMixinState;
  2732. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2733. {
  2734. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2735. mixinState = mixinState->mPrevMixinState;
  2736. }
  2737. return bfError;
  2738. }
  2739. checkMethodState = checkMethodState->mPrevMethodState;
  2740. }
  2741. }
  2742. if (deferError)
  2743. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2744. else if (refNode == NULL)
  2745. bfError = mCompiler->mPassInstance->Fail(errorString);
  2746. else
  2747. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2748. if (bfError != NULL)
  2749. {
  2750. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2751. bfError->mProject = mProject;
  2752. bfError->mIsPersistent = isPersistent;
  2753. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2754. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2755. }
  2756. return bfError;
  2757. }
  2758. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2759. {
  2760. if (mHadBuildError)
  2761. return NULL;
  2762. return Fail(error, refNode);
  2763. }
  2764. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2765. {
  2766. if (mIgnoreErrors)
  2767. return NULL;
  2768. if (refNode != NULL)
  2769. refNode = BfNodeToNonTemporary(refNode);
  2770. mHadBuildError = true;
  2771. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2772. if (bfError != NULL)
  2773. bfError->mProject = mProject;
  2774. return bfError;
  2775. }
  2776. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent, bool showInSpecialized)
  2777. {
  2778. if (mIgnoreErrors || mIgnoreWarnings)
  2779. return NULL;
  2780. if (!mReportErrors)
  2781. {
  2782. mCompiler->mPassInstance->SilentFail();
  2783. return NULL;
  2784. }
  2785. BfAstNode* unwarnNode = refNode;
  2786. //
  2787. {
  2788. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2789. while (parentNodeEntry != NULL)
  2790. {
  2791. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2792. break;
  2793. unwarnNode = parentNodeEntry->mNode;
  2794. parentNodeEntry = parentNodeEntry->mPrev;
  2795. }
  2796. }
  2797. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2798. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2799. {
  2800. return NULL;
  2801. }
  2802. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2803. if (mCurMethodInstance != NULL)
  2804. {
  2805. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2806. {
  2807. if (!showInSpecialized)
  2808. return NULL;
  2809. }
  2810. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2811. return NULL; // No ctorCalcAppend warnings
  2812. }
  2813. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2814. {
  2815. if (!showInSpecialized)
  2816. return NULL;
  2817. }
  2818. if (refNode != NULL)
  2819. refNode = BfNodeToNonTemporary(refNode);
  2820. String warningString = warning;
  2821. bool isWhileSpecializing = false;
  2822. if (!AddErrorContext(warningString, refNode, isWhileSpecializing, true))
  2823. return NULL;
  2824. bool deferWarning = isWhileSpecializing;
  2825. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2826. {
  2827. // We used to bubble up warnings into the mixin injection site, BUT
  2828. // we are now assuming any relevant warnings will be given at the declaration site
  2829. return NULL;
  2830. }
  2831. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2832. {
  2833. BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Emitted code had errors", mCurMethodState->mEmitRefNode);
  2834. if (bfError != NULL)
  2835. mCompiler->mPassInstance->MoreInfo(warningString, refNode);
  2836. return bfError;
  2837. }
  2838. BfError* bfError;
  2839. if (refNode != NULL)
  2840. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warningString, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2841. else
  2842. bfError = mCompiler->mPassInstance->Warn(warningNum, warningString);
  2843. if (bfError != NULL)
  2844. {
  2845. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2846. bfError->mProject = mProject;
  2847. AddFailType(mCurTypeInstance);
  2848. mHadBuildWarning = true;
  2849. bfError->mIsPersistent = isPersistent;
  2850. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2851. {
  2852. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2853. if (parser != NULL)
  2854. {
  2855. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2856. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2857. if (warningNum != 0)
  2858. {
  2859. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  2860. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  2861. }
  2862. }
  2863. }
  2864. }
  2865. return bfError;
  2866. }
  2867. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  2868. {
  2869. if (customAttributes == NULL)
  2870. return;
  2871. auto _AddDeclarationMoreInfo = [&]()
  2872. {
  2873. if (methodInstance != NULL)
  2874. {
  2875. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  2876. mCompiler->mPassInstance->MoreInfo(
  2877. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  2878. methodInstance->mMethodDef->GetRefNode());
  2879. }
  2880. else
  2881. {
  2882. mCompiler->mPassInstance->MoreInfo(
  2883. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  2884. typeInstance->mTypeDef->GetRefNode());
  2885. }
  2886. };
  2887. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  2888. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  2889. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  2890. {
  2891. String err;
  2892. if (methodInstance != NULL)
  2893. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  2894. else
  2895. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2896. bool isError = false;
  2897. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  2898. if (constant->mTypeCode == BfTypeCode_Boolean)
  2899. {
  2900. isError = constant->mBool;
  2901. }
  2902. else if (customAttribute->mCtorArgs.size() >= 2)
  2903. {
  2904. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2905. if (str != NULL)
  2906. {
  2907. err += ":\n '";
  2908. err += *str;
  2909. err += "'";
  2910. }
  2911. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  2912. isError = constant->mBool;
  2913. }
  2914. BfError* error = NULL;
  2915. if (isError)
  2916. error = Fail(err, targetSrc);
  2917. else
  2918. error = Warn(0, err, targetSrc, false, true);
  2919. if (error != NULL)
  2920. _AddDeclarationMoreInfo();
  2921. }
  2922. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  2923. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2924. {
  2925. String err;
  2926. if (methodInstance != NULL)
  2927. err += StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  2928. else
  2929. err += StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2930. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2931. if (str != NULL)
  2932. err += *str;
  2933. err += "'";
  2934. if (Fail(err, targetSrc) != NULL)
  2935. _AddDeclarationMoreInfo();
  2936. }
  2937. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  2938. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  2939. {
  2940. String err;
  2941. if (methodInstance != NULL)
  2942. err += StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  2943. else
  2944. err += StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2945. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2946. if (str != NULL)
  2947. err += *str;
  2948. err += "'";
  2949. if (Warn(0, err, targetSrc, false, true) != NULL)
  2950. _AddDeclarationMoreInfo();
  2951. }
  2952. }
  2953. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2954. {
  2955. if (mBfIRBuilder->mOpFailed)
  2956. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2957. }
  2958. void BfModule::FatalError(const StringImpl& error, const char* file, int line)
  2959. {
  2960. static bool sHadFatalError = false;
  2961. static bool sHadReentrancy = false;
  2962. if (sHadFatalError)
  2963. {
  2964. return;
  2965. sHadReentrancy = true;
  2966. }
  2967. sHadFatalError = true;
  2968. String fullError = error;
  2969. if (file != NULL)
  2970. fullError += StrFormat(" at %s:%d", file, line);
  2971. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  2972. if (mCurTypeInstance != NULL)
  2973. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  2974. if (mCurMethodInstance != NULL)
  2975. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  2976. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  2977. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  2978. if (sHadReentrancy)
  2979. fullError += "\nError had reentrancy";
  2980. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  2981. }
  2982. void BfModule::NotImpl(BfAstNode* astNode)
  2983. {
  2984. Fail("INTERNAL ERROR: Not implemented", astNode);
  2985. }
  2986. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  2987. {
  2988. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2989. if (!allowPrivate)
  2990. allowPrivate |= memberType->IsInterface();
  2991. bool allowProtected = allowPrivate;
  2992. //TODO: We had this commented out, but this makes accessing protected properties fail
  2993. if (mCurTypeInstance != NULL)
  2994. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2995. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  2996. {
  2997. return false;
  2998. }
  2999. return true;
  3000. }
  3001. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  3002. {
  3003. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  3004. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  3005. auto memberTypeInstance = memberType->ToTypeInstance();
  3006. if (memberTypeInstance == NULL)
  3007. {
  3008. auto underlyingType = memberType->GetUnderlyingType();
  3009. if (underlyingType != NULL)
  3010. return CheckDefineMemberProtection(protection, underlyingType);
  3011. return true;
  3012. }
  3013. if (memberTypeInstance->mTypeDef->mProtection < protection)
  3014. return false;
  3015. if (memberTypeInstance->IsGenericTypeInstance())
  3016. {
  3017. // When we're a generic struct, our data layout can depend on our generic parameters as well
  3018. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  3019. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3020. {
  3021. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  3022. return false;
  3023. }
  3024. }
  3025. return true;
  3026. }
  3027. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags, BfDepContext* depContext)
  3028. {
  3029. if (usedType == userType)
  3030. return;
  3031. if (((flags & BfDependencyMap::DependencyFlag_ConstValue) != 0) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_FieldType))
  3032. {
  3033. // This can be an `int32[UsedType.cVal]` type reference
  3034. flags = (BfDependencyMap::DependencyFlags)(flags | BfDependencyMap::DependencyFlag_ValueTypeSizeDep);
  3035. }
  3036. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  3037. {
  3038. if (userType->IsMethodRef())
  3039. {
  3040. // We cannot short-circuit dependencies because of method group ref counting
  3041. }
  3042. else
  3043. return;
  3044. }
  3045. if (usedType->IsSpecializedByAutoCompleteMethod())
  3046. {
  3047. if ((flags & (BfDependencyMap::DependencyFlag_TypeGenericArg | BfDependencyMap::DependencyFlag_OuterType | BfDependencyMap::DependencyFlag_DerivedFrom)) == 0)
  3048. return;
  3049. }
  3050. // if (usedType->IsBoxed())
  3051. // {
  3052. // NOP;
  3053. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  3054. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  3055. // {
  3056. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  3057. // }
  3058. // }
  3059. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  3060. // BfType* origUsedType = usedType;
  3061. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  3062. // if (isDataAccess)
  3063. // {
  3064. // while (true)
  3065. // {
  3066. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  3067. // usedType = usedType->GetUnderlyingType();
  3068. // else if (usedType->IsArray())
  3069. // {
  3070. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  3071. // }
  3072. // else
  3073. // break;
  3074. // }
  3075. // }
  3076. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  3077. {
  3078. bool addType = true;
  3079. auto checkType = usedType;
  3080. PopulateType(checkType, BfPopulateType_Data);
  3081. if (checkType->IsValuelessType())
  3082. addType = false;
  3083. else if (checkType->IsPrimitiveType())
  3084. addType = false;
  3085. else
  3086. {
  3087. auto checkTypeInst = checkType->ToTypeInstance();
  3088. if (checkTypeInst == NULL)
  3089. {
  3090. addType = false;
  3091. }
  3092. else
  3093. {
  3094. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  3095. addType = false;
  3096. }
  3097. }
  3098. if (addType)
  3099. {
  3100. auto checkTypeInst = checkType->ToTypeInstance();
  3101. if (checkTypeInst->mHotTypeData != NULL)
  3102. {
  3103. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  3104. BF_ASSERT(hotTypeVersion != NULL);
  3105. if (hotTypeVersion != NULL)
  3106. {
  3107. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  3108. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  3109. (checkType->IsComposite()))
  3110. isAllocation = true;
  3111. if (isAllocation)
  3112. {
  3113. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  3114. }
  3115. else
  3116. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  3117. }
  3118. }
  3119. }
  3120. }
  3121. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  3122. {
  3123. auto usingModule = userType->GetModule();
  3124. BfModule* usedModule;
  3125. if (usedType->IsFunction())
  3126. {
  3127. if (mCompiler->mFunctionTypeDef != NULL)
  3128. {
  3129. auto functionType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  3130. usedModule = functionType->GetModule();
  3131. }
  3132. }
  3133. else
  3134. usedModule = usedType->GetModule();
  3135. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  3136. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  3137. {
  3138. if ((flags & ~(BfDependencyMap::DependencyFlag_OuterType)) == 0)
  3139. {
  3140. // Not a 'use' dependency
  3141. }
  3142. else
  3143. {
  3144. usingModule->mModuleRefs.Add(usedModule);
  3145. }
  3146. }
  3147. }
  3148. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  3149. {
  3150. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  3151. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  3152. if (genericArg == usedType)
  3153. return;
  3154. }
  3155. auto depFlag = flags;
  3156. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  3157. {
  3158. if (usedType->IsDependendType())
  3159. {
  3160. // Cause a rebuild but not an outright deletion of the type
  3161. // We can only do this if the 'usedType' can actually hold the dependency which can actually trigger a deletion chain
  3162. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef;
  3163. }
  3164. }
  3165. if (usedType->IsTypeAlias())
  3166. {
  3167. auto underlyingType = usedType->GetUnderlyingType();
  3168. if (underlyingType != NULL)
  3169. {
  3170. BfDepContext newDepContext;
  3171. if (depContext == NULL)
  3172. depContext = &newDepContext;
  3173. if (++depContext->mAliasDepth > 8)
  3174. {
  3175. if (!depContext->mDeepSeenAliases.Add(underlyingType))
  3176. return; // Circular!
  3177. }
  3178. AddDependency(underlyingType, userType, depFlag);
  3179. }
  3180. }
  3181. else if (!usedType->IsGenericTypeInstance())
  3182. {
  3183. auto underlyingType = usedType->GetUnderlyingType();
  3184. if (underlyingType != NULL)
  3185. AddDependency(underlyingType, userType, depFlag);
  3186. }
  3187. BfDependedType* checkDType = usedType->ToDependedType();
  3188. if (checkDType == NULL)
  3189. return;
  3190. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  3191. mContext->MarkAsReferenced(checkDType);
  3192. #ifdef _DEBUG
  3193. // If a MethodRef depends ON US, that means it's a local method that we own
  3194. if (userType->IsMethodRef())
  3195. {
  3196. auto methodRefType = (BfMethodRefType*)userType;
  3197. BF_ASSERT(methodRefType->mOwner == checkDType);
  3198. }
  3199. #endif
  3200. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  3201. return;
  3202. if ((checkDType->IsGenericTypeInstance()) && (!userType->IsMethodRef()))
  3203. {
  3204. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  3205. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3206. {
  3207. AddDependency(genericArg, userType, depFlag);
  3208. }
  3209. }
  3210. if (checkDType->IsTuple())
  3211. {
  3212. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  3213. {
  3214. if (field.mDataIdx != -1)
  3215. AddDependency(field.mResolvedType, userType, depFlag);
  3216. }
  3217. }
  3218. }
  3219. void BfModule::AddDependency(BfGenericParamInstance* genericParam, BfTypeInstance* usingType)
  3220. {
  3221. if ((genericParam->mExternType != NULL) && (!genericParam->mExternType->IsGenericParam()))
  3222. AddDependency(genericParam->mExternType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3223. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  3224. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3225. for (auto& operatorConstraint : genericParam->mOperatorConstraints)
  3226. {
  3227. if (operatorConstraint.mLeftType != NULL)
  3228. AddDependency(operatorConstraint.mLeftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3229. if (operatorConstraint.mRightType != NULL)
  3230. AddDependency(operatorConstraint.mRightType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3231. }
  3232. if (genericParam->mTypeConstraint != NULL)
  3233. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3234. }
  3235. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  3236. {
  3237. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  3238. {
  3239. if (methodInstance->mHotMethod == NULL)
  3240. CheckHotMethod(methodInstance, "");
  3241. BF_ASSERT(methodInstance->mHotMethod != NULL);
  3242. if (devirtualized)
  3243. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  3244. else
  3245. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  3246. }
  3247. }
  3248. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  3249. {
  3250. auto checkTypeInst = typeInst;
  3251. while (checkTypeInst != NULL)
  3252. {
  3253. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  3254. return true;
  3255. checkTypeInst = checkTypeInst->mBaseType;
  3256. }
  3257. return false;
  3258. }
  3259. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  3260. {
  3261. if (mContext->mCurTypeState == NULL)
  3262. return;
  3263. BP_ZONE("PopulateGlobalContainersList");
  3264. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  3265. if ((userTypeDef == NULL) && (mCurMethodInstance != NULL))
  3266. userTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  3267. if (userTypeDef == NULL)
  3268. userTypeDef = mCurTypeInstance->mTypeDef;
  3269. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  3270. {
  3271. mContext->mCurTypeState->mGlobalContainers.Clear();
  3272. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  3273. {
  3274. BfAtomComposite findStr;
  3275. if (namespaceIdx != -1)
  3276. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  3277. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  3278. while (typeDefItr)
  3279. {
  3280. auto typeDef = *typeDefItr;
  3281. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  3282. {
  3283. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  3284. {
  3285. BfGlobalContainerEntry globalEntry;
  3286. globalEntry.mTypeDef = typeDef;
  3287. globalEntry.mTypeInst = NULL;
  3288. typeDef->PopulateMemberSets();
  3289. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  3290. }
  3291. }
  3292. else if (!typeDef->mIsPartial)
  3293. {
  3294. //break;
  3295. }
  3296. typeDefItr.MoveToNextHashMatch();
  3297. }
  3298. }
  3299. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  3300. }
  3301. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  3302. // reifing types
  3303. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  3304. {
  3305. if (globalEntry.mTypeInst == NULL)
  3306. {
  3307. bool include = false;
  3308. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  3309. include = true;
  3310. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  3311. {
  3312. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  3313. include = true;
  3314. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  3315. include = true;
  3316. }
  3317. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  3318. {
  3319. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  3320. include = true;
  3321. }
  3322. if (include)
  3323. {
  3324. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  3325. if (type != NULL)
  3326. globalEntry.mTypeInst = type->ToTypeInstance();
  3327. }
  3328. }
  3329. }
  3330. }
  3331. BfStaticSearch* BfModule::GetStaticSearch()
  3332. {
  3333. auto activeTypeDef = GetActiveTypeDef();
  3334. BfStaticSearch* staticSearch = NULL;
  3335. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3336. return staticSearch;
  3337. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3338. return staticSearch;
  3339. return NULL;
  3340. }
  3341. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  3342. {
  3343. auto activeTypeDef = GetActiveTypeDef();
  3344. BfInternalAccessSet* internalAccessSet = NULL;
  3345. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3346. return internalAccessSet;
  3347. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3348. return internalAccessSet;
  3349. return NULL;
  3350. }
  3351. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  3352. {
  3353. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  3354. return true;
  3355. if ((mCurMethodInstance != NULL) &&
  3356. ((mCurMethodInstance->mIsUnspecializedVariation) || (mCurMethodInstance->IsSpecializedGenericMethod())))
  3357. return true;
  3358. auto internalAccessSet = GetInternalAccessSet();
  3359. if (internalAccessSet == NULL)
  3360. return false;
  3361. for (auto& nameComposite : internalAccessSet->mNamespaces)
  3362. {
  3363. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  3364. return true;
  3365. }
  3366. for (auto internalType : internalAccessSet->mTypes)
  3367. {
  3368. auto checkTypeDef = usingTypeDef->GetDefinition();
  3369. while (checkTypeDef != NULL)
  3370. {
  3371. if (checkTypeDef == internalType->mTypeDef->GetDefinition())
  3372. return true;
  3373. checkTypeDef = checkTypeDef->mOuterType;
  3374. }
  3375. }
  3376. return false;
  3377. }
  3378. void PrintUsers(llvm::MDNode* md);
  3379. BfModuleOptions BfModule::GetModuleOptions()
  3380. {
  3381. if (mIsScratchModule)
  3382. return BfModuleOptions();
  3383. if (mModuleOptions != NULL)
  3384. return *mModuleOptions;
  3385. BfModuleOptions moduleOptions;
  3386. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3387. if (mProject != NULL)
  3388. {
  3389. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3390. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3391. }
  3392. auto headModule = this;
  3393. while (headModule->mParentModule != NULL)
  3394. headModule = headModule->mParentModule;
  3395. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata") || mIsSpecialModule);
  3396. if (headModule->mOwnedTypeInstances.size() > 0)
  3397. {
  3398. auto typeInst = headModule->mOwnedTypeInstances[0];
  3399. if (typeInst->mTypeOptionsIdx == -2)
  3400. PopulateType(typeInst);
  3401. if (typeInst->mTypeOptionsIdx != -1)
  3402. {
  3403. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3404. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3405. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3406. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3407. }
  3408. }
  3409. return moduleOptions;
  3410. }
  3411. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3412. {
  3413. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3414. return BfCheckedKind_Unchecked;
  3415. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3416. auto typeOptions = GetTypeOptions();
  3417. if (typeOptions != NULL)
  3418. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3419. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3420. }
  3421. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3422. {
  3423. BF_ASSERT(typeInstance != NULL);
  3424. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_InFailTypes) != 0)
  3425. return;
  3426. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_InFailTypes);
  3427. mContext->mFailTypes.Add(typeInstance);
  3428. }
  3429. void BfModule::DeferRebuildType(BfTypeInstance* typeInstance)
  3430. {
  3431. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_RebuildQueued) != 0)
  3432. return;
  3433. mCompiler->mHasQueuedTypeRebuilds = true;
  3434. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_RebuildQueued);
  3435. AddFailType(typeInstance);
  3436. }
  3437. void BfModule::CheckAddFailType()
  3438. {
  3439. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3440. // but we still need to add the owning type to the FailTypes list
  3441. //.. OLD:
  3442. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3443. /*if (mCurTypeInstance->mModule != this)
  3444. return;*/
  3445. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3446. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3447. // being recompiled. This forces types with warnings to be recompiled.
  3448. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3449. // constantly warning-aware
  3450. if ((mHadBuildError) ||
  3451. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3452. {
  3453. //mContext->mFailTypes.Add(mCurTypeInstance);
  3454. }
  3455. }
  3456. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3457. {
  3458. if (!mCompiler->IsHotCompile())
  3459. return;
  3460. typeInst->mDirty = true;
  3461. for (auto& dep : typeInst->mDependencyMap)
  3462. {
  3463. auto depType = dep.mKey;
  3464. auto depFlags = dep.mValue.mFlags;
  3465. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3466. {
  3467. MarkDerivedDirty(depType->ToTypeInstance());
  3468. }
  3469. }
  3470. }
  3471. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3472. {
  3473. auto fieldType = fieldInstance->GetResolvedType();
  3474. auto field = fieldInstance->GetFieldDef();
  3475. if (fieldType->IsVar())
  3476. return;
  3477. BfIRValue initValue;
  3478. if (field->mIsConst)
  3479. {
  3480. if (fieldType->IsPointer())
  3481. fieldType = fieldType->GetUnderlyingType();
  3482. }
  3483. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3484. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3485. storageKind = BfIRStorageKind_Export;
  3486. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3487. storageKind = BfIRStorageKind_Import;
  3488. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3489. initValue = GetDefaultValue(fieldType);
  3490. if (fieldInstance->mOwner->IsUnspecializedType())
  3491. {
  3492. // Placeholder
  3493. auto ptrVal = CreatePointerType(fieldType);
  3494. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3495. }
  3496. else
  3497. {
  3498. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3499. StringT<128> staticVarName;
  3500. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3501. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3502. {
  3503. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3504. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  3505. false,
  3506. BfIRLinkageType_External,
  3507. initValue,
  3508. staticVarName,
  3509. isThreadLocal);
  3510. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3511. if (storageKind != BfIRStorageKind_Normal)
  3512. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3513. BF_ASSERT(globalVar);
  3514. mStaticFieldRefs[fieldInstance] = globalVar;
  3515. }
  3516. }
  3517. }
  3518. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3519. {
  3520. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3521. BfType* fieldType = NULL;
  3522. if (fieldInstance != NULL)
  3523. {
  3524. fieldType = fieldInstance->GetResolvedType();
  3525. if (fieldType == NULL)
  3526. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3527. }
  3528. else
  3529. {
  3530. BF_ASSERT(mCompiler->IsAutocomplete());
  3531. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3532. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3533. {
  3534. fieldType = typeInstance;
  3535. }
  3536. else
  3537. {
  3538. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3539. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3540. if (isLet || isVar)
  3541. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3542. else
  3543. fieldType = ResolveTypeRef(fieldDef->mTypeRef,BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  3544. if (fieldType == NULL)
  3545. fieldType = mContext->mBfObjectType;
  3546. }
  3547. }
  3548. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3549. return;
  3550. if (mContext->mFieldResolveReentrys.size() > 1)
  3551. {
  3552. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3553. {
  3554. String failStr = "Circular data reference detected between the following fields:";
  3555. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3556. {
  3557. if (i > 1)
  3558. failStr += ",";
  3559. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3560. }
  3561. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3562. if (err)
  3563. err->mIsPersistent = true;
  3564. return;
  3565. }
  3566. }
  3567. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3568. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3569. if (fieldInstance == NULL)
  3570. popTypeResolveReentry.Pop();
  3571. auto typeDef = typeInstance->mTypeDef;
  3572. BfIRValue constValue;
  3573. if (fieldDef->mIsExtern)
  3574. {
  3575. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3576. {
  3577. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3578. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  3579. }
  3580. if (fieldDef->mInitializer != NULL)
  3581. {
  3582. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3583. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  3584. }
  3585. }
  3586. else if (fieldDef->mInitializer == NULL)
  3587. {
  3588. if (fieldDef->IsEnumCaseEntry())
  3589. {
  3590. if (typeInstance->IsTypedPrimitive())
  3591. {
  3592. BfFieldInstance* prevFieldInstance = NULL;
  3593. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3594. {
  3595. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3596. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3597. {
  3598. prevFieldInstance = checkFieldInst;
  3599. break;
  3600. }
  3601. }
  3602. if (prevFieldInstance == NULL)
  3603. constValue = GetConstValue(0, typeInstance);
  3604. else
  3605. {
  3606. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3607. if (prevFieldInstance->mConstIdx == -1)
  3608. {
  3609. if (!mCompiler->IsAutocomplete())
  3610. AssertErrorState();
  3611. constValue = GetConstValue(0, typeInstance);
  3612. }
  3613. else
  3614. {
  3615. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3616. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3617. }
  3618. }
  3619. }
  3620. }
  3621. else
  3622. {
  3623. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  3624. }
  3625. }
  3626. else if (mBfIRBuilder != NULL)
  3627. {
  3628. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3629. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3630. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3631. BfMethodState methodState;
  3632. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3633. methodState.mTempKind = BfMethodState::TempKind_Static;
  3634. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3635. if ((fieldType->IsVar()) || (fieldType->IsUndefSizedArray()))
  3636. {
  3637. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  3638. if (!initValue)
  3639. {
  3640. AssertErrorState();
  3641. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3642. }
  3643. if (fieldInstance != NULL)
  3644. {
  3645. if (fieldType->IsUndefSizedArray())
  3646. {
  3647. if ((initValue.mType->IsSizedArray()) && (initValue.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3648. {
  3649. fieldInstance->mResolvedType = initValue.mType;
  3650. }
  3651. }
  3652. else
  3653. fieldInstance->mResolvedType = initValue.mType;
  3654. }
  3655. constValue = initValue.mValue;
  3656. }
  3657. else
  3658. {
  3659. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  3660. constValue = uncastedInitValue.mValue;
  3661. }
  3662. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3663. {
  3664. // Illegal
  3665. constValue = BfIRValue();
  3666. }
  3667. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3668. }
  3669. if (fieldInstance != NULL)
  3670. {
  3671. fieldType = fieldInstance->GetResolvedType();
  3672. if ((fieldType == NULL) || (fieldType->IsVar()))
  3673. {
  3674. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3675. AssertErrorState();
  3676. // Default const type is 'int'
  3677. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3678. if (fieldInstance != NULL)
  3679. {
  3680. fieldInstance->mResolvedType = initValue.mType;
  3681. }
  3682. constValue = initValue.mValue;
  3683. }
  3684. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3685. {
  3686. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3687. CurrentAddToConstHolder(constValue);
  3688. fieldInstance->mConstIdx = constValue.mId;
  3689. }
  3690. }
  3691. }
  3692. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3693. {
  3694. bool isDeclType = (field->mFieldDeclaration != NULL) && BfNodeDynCastExact<BfExprModTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  3695. auto fieldType = fieldInstance->GetResolvedType();
  3696. if ((field->mIsConst) && (!isDeclType))
  3697. {
  3698. ResolveConstField(typeInstance, fieldInstance, field);
  3699. return fieldInstance->GetResolvedType();
  3700. }
  3701. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3702. if (!fieldInstance->mIsInferredType)
  3703. return fieldType;
  3704. if ((!fieldType->IsVar()) && (!fieldType->IsUndefSizedArray()))
  3705. return fieldType;
  3706. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3707. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3708. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mType != typeInstance);
  3709. auto typeDef = typeInstance->mTypeDef;
  3710. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3711. {
  3712. AssertErrorState();
  3713. return fieldType;
  3714. }
  3715. bool hadInferenceCycle = false;
  3716. if (mContext->mFieldResolveReentrys.size() > 1)
  3717. {
  3718. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3719. {
  3720. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3721. {
  3722. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3723. auto fieldDef = fieldInst->GetFieldDef();
  3724. auto fieldOwner = fieldInst->mOwner;
  3725. auto fieldModule = fieldOwner->mModule;
  3726. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3727. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3728. }
  3729. return fieldType;
  3730. }
  3731. }
  3732. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3733. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3734. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3735. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3736. if ((field->mInitializer == NULL) && (!isDeclType))
  3737. {
  3738. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3739. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3740. return fieldType;
  3741. }
  3742. BfType* resolvedType = NULL;
  3743. if (!hadInferenceCycle)
  3744. {
  3745. BfTypeState typeState;
  3746. typeState.mPrevState = mContext->mCurTypeState;
  3747. typeState.mType = typeInstance;
  3748. typeState.mCurFieldDef = field;
  3749. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3750. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3751. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3752. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3753. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3754. BfMethodState methodState;
  3755. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3756. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3757. if (!staticOnly)
  3758. {
  3759. //BfLocalVariable localVar;
  3760. //methodState.mLocals.push_back(localVar);
  3761. }
  3762. if (isDeclType)
  3763. {
  3764. auto fieldDef = fieldInstance->GetFieldDef();
  3765. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3766. }
  3767. else
  3768. {
  3769. BfTypedValue valueFromExpr;
  3770. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3771. FixIntUnknown(valueFromExpr);
  3772. if (fieldType->IsUndefSizedArray())
  3773. {
  3774. if ((valueFromExpr.mType != NULL) && (valueFromExpr.mType->IsSizedArray()) && (valueFromExpr.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3775. resolvedType = valueFromExpr.mType;
  3776. }
  3777. else
  3778. resolvedType = valueFromExpr.mType;
  3779. }
  3780. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3781. }
  3782. if (resolvedType == NULL)
  3783. return fieldType;
  3784. fieldInstance->SetResolvedType(resolvedType);
  3785. if (field->mIsStatic)
  3786. {
  3787. }
  3788. else if (fieldInstance->mDataIdx >= 0)
  3789. {
  3790. }
  3791. else
  3792. {
  3793. BF_ASSERT(typeInstance->IsIncomplete());
  3794. }
  3795. return resolvedType;
  3796. }
  3797. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3798. {
  3799. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3800. auto fieldType = fieldInstance->GetResolvedType();
  3801. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3802. {
  3803. int fieldIdx = 0;
  3804. int fieldCount = 0;
  3805. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  3806. fieldIdx--;
  3807. int count = fieldCount;
  3808. if (fieldIdx == -1)
  3809. count = 1;
  3810. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3811. auto thisVariable = GetThisVariable();
  3812. if (thisVariable != NULL)
  3813. {
  3814. for (int i = 0; i < count; i++)
  3815. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  3816. }
  3817. }
  3818. }
  3819. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3820. {
  3821. if (fieldInstance->mCustomAttributes == NULL)
  3822. return false;
  3823. auto fieldDef = fieldInstance->GetFieldDef();
  3824. if (!fieldDef->mIsStatic)
  3825. return false;
  3826. bool isThreadLocal = false;
  3827. if (fieldInstance->mCustomAttributes != NULL)
  3828. {
  3829. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3830. {
  3831. if (customAttr.mType->ToTypeInstance()->IsInstanceOf(mCompiler->mThreadStaticAttributeTypeDef))
  3832. return true;
  3833. }
  3834. }
  3835. return false;
  3836. }
  3837. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  3838. {
  3839. if (fieldDef == NULL)
  3840. fieldDef = fieldInstance->GetFieldDef();
  3841. if (fieldType == NULL)
  3842. fieldType = fieldInstance->GetResolvedType();
  3843. if (initializer == NULL)
  3844. {
  3845. if (fieldDef == NULL)
  3846. return BfTypedValue();
  3847. initializer = fieldDef->mInitializer;
  3848. }
  3849. BfTypedValue staticVarRef;
  3850. BfTypedValue result;
  3851. if (initializer == NULL)
  3852. {
  3853. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3854. }
  3855. else
  3856. {
  3857. if (mCompiler->mIsResolveOnly)
  3858. {
  3859. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  3860. {
  3861. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3862. sourceClassifier->VisitChildNoRef(initializer);
  3863. }
  3864. }
  3865. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3866. {
  3867. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3868. BfConstResolver constResolver(this);
  3869. constResolver.Resolve(initializer);
  3870. return GetDefaultTypedValue(fieldType);
  3871. }
  3872. else if (fieldDef->mIsConst)
  3873. {
  3874. int ceExecuteId = -1;
  3875. if (mCompiler->mCeMachine != NULL)
  3876. ceExecuteId = mCompiler->mCeMachine->mExecuteId;
  3877. BfTypeState typeState;
  3878. typeState.mType = mCurTypeInstance;
  3879. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3880. typeState.mCurFieldDef = fieldDef;
  3881. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3882. BfConstResolver constResolver(this);
  3883. if (fieldType->IsVar())
  3884. return constResolver.Resolve(initializer);
  3885. else
  3886. {
  3887. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  3888. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  3889. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  3890. {
  3891. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  3892. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  3893. resolveFlags = BfConstResolveFlag_NoCast;
  3894. }
  3895. UpdateSrcPos(initializer);
  3896. auto result = constResolver.Resolve(initializer, fieldType, resolveFlags);
  3897. if ((mCompiler->mCeMachine != NULL) && (fieldInstance != NULL))
  3898. {
  3899. if (mCompiler->mCeMachine->mExecuteId != ceExecuteId)
  3900. fieldInstance->mHadConstEval = true;
  3901. }
  3902. return result;
  3903. }
  3904. }
  3905. BfExprEvaluator exprEvaluator(this);
  3906. if (doStore)
  3907. {
  3908. staticVarRef = ReferenceStaticField(fieldInstance);
  3909. exprEvaluator.mReceivingValue = &staticVarRef;
  3910. }
  3911. if (fieldType->IsVar())
  3912. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3913. else
  3914. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3915. if (doStore)
  3916. {
  3917. if (exprEvaluator.mReceivingValue == NULL)
  3918. doStore = false; // Already stored
  3919. }
  3920. }
  3921. if (fieldInstance != NULL)
  3922. MarkFieldInitialized(fieldInstance);
  3923. if ((doStore) && (result))
  3924. {
  3925. if (fieldInstance->mResolvedType->IsUndefSizedArray())
  3926. {
  3927. if ((!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mFastFinish))
  3928. AssertErrorState();
  3929. }
  3930. else
  3931. {
  3932. result = LoadValue(result);
  3933. if (!result.mType->IsValuelessType())
  3934. mBfIRBuilder->CreateStore(result.mValue, staticVarRef.mValue);
  3935. }
  3936. }
  3937. return result;
  3938. }
  3939. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3940. {
  3941. }
  3942. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3943. {
  3944. PopulateType(classType);
  3945. if (isInterfacePass)
  3946. {
  3947. for (auto ifaceInst : classType->mInterfaces)
  3948. {
  3949. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3950. continue;
  3951. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3952. continue;
  3953. if (ifaceInst.mDeclaringType->IsExtension())
  3954. {
  3955. bool needsExCheck = false;
  3956. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3957. {
  3958. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  3959. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  3960. {
  3961. exChecks->push_back(ifaceInst.mInterfaceType);
  3962. continue;
  3963. }
  3964. else
  3965. {
  3966. // We can only do an 'exCheck' if we're actually going to slot this interface
  3967. }
  3968. }
  3969. }
  3970. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3971. }
  3972. }
  3973. else
  3974. {
  3975. outVals->push_back(classType->mTypeId);
  3976. }
  3977. if (classType->mBaseType != NULL)
  3978. {
  3979. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3980. }
  3981. }
  3982. void BfModule::CreateDynamicCastMethod()
  3983. {
  3984. auto objType = mContext->mBfObjectType;
  3985. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3986. {
  3987. // The main reason to punt on this method for ResolveOnly is because types can be created
  3988. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3989. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3990. // remove this punt when we recycle typeId's
  3991. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3992. mCurMethodState->mHadReturn = true;
  3993. return;
  3994. }
  3995. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3996. auto func = mCurMethodState->mIRFunction;
  3997. auto thisValue = mBfIRBuilder->GetArgument(0);
  3998. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3999. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4000. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  4001. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  4002. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  4003. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  4004. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  4005. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4006. SizedArray<int, 8> typeMatches;
  4007. SizedArray<BfTypeInstance*, 8> exChecks;
  4008. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  4009. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  4010. {
  4011. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  4012. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  4013. BfTypeVector genericArgs;
  4014. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  4015. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  4016. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef->GetDefinition(), genericArgs, BfPopulateType_Declaration);
  4017. typeMatches.push_back(unboundType->mTypeId);
  4018. }
  4019. if (mCurTypeInstance->IsBoxed())
  4020. {
  4021. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  4022. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  4023. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  4024. if (innerType->IsTypedPrimitive())
  4025. {
  4026. auto underlyingType = innerType->GetUnderlyingType();
  4027. typeMatches.push_back(underlyingType->mTypeId);
  4028. }
  4029. auto innerTypeInst = innerType->ToTypeInstance();
  4030. if ((innerTypeInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef)) ||
  4031. (innerTypeInst->IsInstanceOf(mCompiler->mPointerTTypeDef)) ||
  4032. (innerTypeInst->IsInstanceOf(mCompiler->mMethodRefTypeDef)))
  4033. {
  4034. PopulateType(innerTypeInst);
  4035. //TODO: What case was this supposed to handle?
  4036. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  4037. }
  4038. }
  4039. auto curBlock = mBfIRBuilder->GetInsertBlock();
  4040. BfIRValue vDataPtr;
  4041. if (!exChecks.empty())
  4042. {
  4043. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4044. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  4045. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  4046. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4047. }
  4048. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  4049. for (auto typeMatch : typeMatches)
  4050. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  4051. Array<BfIRValue> incomingFalses;
  4052. for (auto ifaceTypeInst : exChecks)
  4053. {
  4054. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  4055. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  4056. mBfIRBuilder->SetInsertPoint(nextBB);
  4057. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  4058. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4059. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4060. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4061. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  4062. incomingFalses.push_back(nextBB);
  4063. }
  4064. mBfIRBuilder->AddBlock(trueBB);
  4065. mBfIRBuilder->SetInsertPoint(trueBB);
  4066. mBfIRBuilder->CreateBr(exitBB);
  4067. mBfIRBuilder->AddBlock(exitBB);
  4068. mBfIRBuilder->SetInsertPoint(exitBB);
  4069. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  4070. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  4071. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  4072. for (auto incomingFalseBlock : incomingFalses)
  4073. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  4074. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  4075. mBfIRBuilder->CreateRet(phi);
  4076. mCurMethodState->mHadReturn = true;
  4077. }
  4078. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  4079. {
  4080. BfExprEvaluator exprEvaluator(this);
  4081. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  4082. auto typeInst = rightValue.mType->ToTypeInstance();
  4083. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  4084. BfTypedValue result = exprEvaluator.GetResult();
  4085. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  4086. {
  4087. // Fail?
  4088. }
  4089. if ((result) && (!result.mType->IsVar()))
  4090. {
  4091. auto nextBB = mBfIRBuilder->CreateBlock("next");
  4092. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  4093. mBfIRBuilder->AddBlock(nextBB);
  4094. mBfIRBuilder->SetInsertPoint(nextBB);
  4095. }
  4096. }
  4097. void BfModule::CreateFakeCallerMethod(const String& funcName)
  4098. {
  4099. if (mCurMethodInstance->mHasFailed)
  4100. return;
  4101. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  4102. return;
  4103. BF_ASSERT(mCurMethodInstance->mIRFunction);
  4104. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  4105. SizedArray<BfIRType, 4> paramTypes;
  4106. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  4107. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  4108. mBfIRBuilder->SetActiveFunction(func);
  4109. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  4110. mBfIRBuilder->SetInsertPoint(entryBlock);
  4111. BfMethodState methodState;
  4112. methodState.mIRHeadBlock = entryBlock;
  4113. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4114. SizedArray<BfIRValue, 8> args;
  4115. BfExprEvaluator exprEvaluator(this);
  4116. if (mCurMethodInstance->GetStructRetIdx() == 0)
  4117. {
  4118. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4119. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4120. }
  4121. if (mCurMethodInstance->HasThis())
  4122. {
  4123. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  4124. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  4125. }
  4126. if (mCurMethodInstance->GetStructRetIdx() == 1)
  4127. {
  4128. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4129. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4130. }
  4131. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  4132. {
  4133. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  4134. if (paramType->IsValuelessType())
  4135. continue;
  4136. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  4137. }
  4138. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  4139. mBfIRBuilder->CreateRetVoid();
  4140. }
  4141. void BfModule::CreateDelegateEqualsMethod()
  4142. {
  4143. if (mBfIRBuilder->mIgnoreWrites)
  4144. return;
  4145. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4146. if (refNode == NULL)
  4147. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4148. UpdateSrcPos(refNode);
  4149. SetIllegalSrcPos();
  4150. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4151. auto resultVal = CreateAlloca(boolType);
  4152. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4153. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4154. auto delegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  4155. mBfIRBuilder->PopulateType(delegateType);
  4156. BfExprEvaluator exprEvaluator(this);
  4157. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4158. BfTypedValue lhsDelegate = BfTypedValue(mBfIRBuilder->CreateBitCast(leftTypedVal.mValue, mBfIRBuilder->MapType(delegateType)), delegateType);
  4159. BfTypedValue rhsDelegate = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4160. rhsDelegate = LoadValue(rhsDelegate);
  4161. BfTypedValue rightTypedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(rhsDelegate.mValue, mBfIRBuilder->MapType(mCurTypeInstance)), mCurTypeInstance);
  4162. auto& targetFieldInstance = delegateType->mFieldInstances[0];
  4163. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(lhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4164. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4165. leftValue = LoadValue(leftValue);
  4166. rightValue = LoadValue(rightValue);
  4167. EmitEquals(leftValue, rightValue, exitBB, false);
  4168. bool hadComparison = false;
  4169. for (auto& fieldRef : mCurTypeInstance->mFieldInstances)
  4170. {
  4171. BfFieldInstance* fieldInstance = &fieldRef;
  4172. if (fieldInstance->mDataOffset == -1)
  4173. continue;
  4174. auto fieldType = fieldInstance->mResolvedType;
  4175. if (fieldType->IsValuelessType())
  4176. continue;
  4177. if (fieldType->IsVar())
  4178. continue;
  4179. if (fieldType->IsMethodRef())
  4180. continue;
  4181. if (fieldType->IsRef())
  4182. fieldType = CreatePointerType(fieldType->GetUnderlyingType());
  4183. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(leftTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4184. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rightTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4185. if (!fieldInstance->mResolvedType->IsComposite())
  4186. {
  4187. leftValue = LoadValue(leftValue);
  4188. rightValue = LoadValue(rightValue);
  4189. }
  4190. EmitEquals(leftValue, rightValue, exitBB, false);
  4191. }
  4192. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4193. mBfIRBuilder->CreateBr(exitBB);
  4194. mBfIRBuilder->AddBlock(exitBB);
  4195. mBfIRBuilder->SetInsertPoint(exitBB);
  4196. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4197. ClearLifetimeEnds();
  4198. mBfIRBuilder->CreateRet(loadedResult);
  4199. mCurMethodState->mHadReturn = true;
  4200. }
  4201. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  4202. {
  4203. if (mCurMethodInstance->mIsUnspecialized)
  4204. return;
  4205. if (mBfIRBuilder->mIgnoreWrites)
  4206. return;
  4207. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  4208. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  4209. bool isValid = true;
  4210. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4211. if (compareType->IsValuelessType())
  4212. {
  4213. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4214. return;
  4215. }
  4216. if (compareType->IsTypedPrimitive())
  4217. {
  4218. BfExprEvaluator exprEvaluator(this);
  4219. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  4220. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  4221. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  4222. mBfIRBuilder->CreateRet(cmpResult);
  4223. return;
  4224. }
  4225. auto compareDType = compareType->ToDependedType();
  4226. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  4227. if (compareTypeInst != NULL)
  4228. {
  4229. if (compareType->IsPrimitiveType())
  4230. compareTypeInst = GetWrappedStructType(compareType);
  4231. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  4232. {
  4233. isValid = false;
  4234. }
  4235. mBfIRBuilder->PopulateType(compareTypeInst);
  4236. }
  4237. if (!isValid)
  4238. {
  4239. ClearLifetimeEnds();
  4240. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4241. return;
  4242. }
  4243. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  4244. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4245. if (refNode == NULL)
  4246. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4247. UpdateSrcPos(refNode);
  4248. SetIllegalSrcPos();
  4249. auto resultVal = CreateAlloca(boolType);
  4250. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4251. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4252. if (compareType->IsValuelessType())
  4253. {
  4254. // Always equal, nothing to do
  4255. }
  4256. else if (compareType->IsSizedArray())
  4257. {
  4258. auto sizedArrayType = (BfSizedArrayType*)compareType;
  4259. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  4260. {
  4261. BfTypedValue result;
  4262. // if (sizedArrayType->mElementType->IsSizeAligned())
  4263. // {
  4264. // auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  4265. // auto ptrValue = mBfIRBuilder->CreateBitCast(target, mBfIRBuilder->MapType(ptrType));
  4266. // auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, index);
  4267. // result = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4268. // }
  4269. // else
  4270. // {
  4271. // auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index);
  4272. // result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4273. // }
  4274. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index, true);
  4275. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4276. if (!result.mType->IsValueType())
  4277. result = LoadValue(result);
  4278. return result;
  4279. };
  4280. if (sizedArrayType->mElementCount > 6)
  4281. {
  4282. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4283. auto itr = CreateAlloca(intPtrType);
  4284. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  4285. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  4286. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  4287. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  4288. mBfIRBuilder->CreateBr(loopBB);
  4289. mBfIRBuilder->SetInsertPoint(loopBB);
  4290. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  4291. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  4292. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  4293. mBfIRBuilder->SetInsertPoint(bodyBB);
  4294. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  4295. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  4296. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4297. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  4298. mBfIRBuilder->CreateStore(incValue, itr);
  4299. mBfIRBuilder->CreateBr(loopBB);
  4300. mBfIRBuilder->SetInsertPoint(doneBB);
  4301. }
  4302. else
  4303. {
  4304. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  4305. {
  4306. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4307. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4308. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4309. }
  4310. }
  4311. }
  4312. else if (compareType->IsMethodRef())
  4313. {
  4314. auto methodRefType = (BfMethodRefType*)compareType;
  4315. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  4316. BfExprEvaluator exprEvaluator(this);
  4317. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4318. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4319. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  4320. // values for the same method reference -- they will always refer back to the same local variables.
  4321. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  4322. if (dataIdx != -1)
  4323. {
  4324. bool failed = false;
  4325. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  4326. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  4327. BF_ASSERT(!failed);
  4328. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4329. }
  4330. }
  4331. else if (compareTypeInst->IsEnum())
  4332. {
  4333. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4334. BfExprEvaluator exprEvaluator(this);
  4335. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4336. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4337. auto dscrType = compareTypeInst->GetDiscriminatorType();
  4338. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  4339. leftValue = LoadValue(leftValue);
  4340. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  4341. rightValue = LoadValue(rightValue);
  4342. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  4343. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  4344. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4345. int enumCount = 0;
  4346. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4347. {
  4348. BfFieldInstance* fieldInstance = &fieldRef;
  4349. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4350. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4351. {
  4352. enumCount = -fieldInstance->mDataIdx;
  4353. }
  4354. }
  4355. if (enumCount > 0)
  4356. {
  4357. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  4358. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  4359. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4360. {
  4361. BfFieldInstance* fieldInstance = &fieldRef;
  4362. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4363. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4364. {
  4365. int enumIdx = -fieldInstance->mDataIdx - 1;
  4366. if (fieldInstance->mResolvedType->mSize == 0)
  4367. {
  4368. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  4369. }
  4370. else
  4371. {
  4372. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  4373. mBfIRBuilder->SetInsertPoint(caseBlock);
  4374. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  4375. BfTypedValue leftTuple;
  4376. BfTypedValue rightTuple;
  4377. if (leftPayload.IsAddr())
  4378. {
  4379. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4380. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4381. }
  4382. else
  4383. {
  4384. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4385. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4386. }
  4387. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  4388. mBfIRBuilder->CreateBr(matchedBlock);
  4389. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  4390. }
  4391. }
  4392. }
  4393. mBfIRBuilder->AddBlock(matchedBlock);
  4394. mBfIRBuilder->SetInsertPoint(matchedBlock);
  4395. }
  4396. }
  4397. else if (compareTypeInst->IsUnion())
  4398. {
  4399. auto innerType = compareTypeInst->GetUnionInnerType();
  4400. if (!innerType->IsValuelessType())
  4401. {
  4402. BfExprEvaluator exprEvaluator(this);
  4403. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4404. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  4405. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4406. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  4407. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  4408. }
  4409. }
  4410. else
  4411. {
  4412. BfExprEvaluator exprEvaluator(this);
  4413. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4414. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4415. bool hadComparison = false;
  4416. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4417. {
  4418. BfFieldInstance* fieldInstance = &fieldRef;
  4419. if (fieldInstance->mDataOffset == -1)
  4420. continue;
  4421. if (fieldInstance->mResolvedType->IsValuelessType())
  4422. continue;
  4423. if (fieldInstance->mResolvedType->IsVar())
  4424. continue;
  4425. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4426. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4427. if (!fieldInstance->mResolvedType->IsComposite())
  4428. {
  4429. leftValue = LoadValue(leftValue);
  4430. rightValue = LoadValue(rightValue);
  4431. }
  4432. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4433. }
  4434. auto baseTypeInst = compareTypeInst->mBaseType;
  4435. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  4436. {
  4437. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  4438. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  4439. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4440. }
  4441. }
  4442. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4443. mBfIRBuilder->CreateBr(exitBB);
  4444. mBfIRBuilder->AddBlock(exitBB);
  4445. mBfIRBuilder->SetInsertPoint(exitBB);
  4446. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4447. ClearLifetimeEnds();
  4448. mBfIRBuilder->CreateRet(loadedResult);
  4449. mCurMethodState->mHadReturn = true;
  4450. }
  4451. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  4452. {
  4453. if (mBfIRBuilder->mIgnoreWrites)
  4454. return mBfIRBuilder->GetFakeVal();
  4455. PopulateType(typeInstance, mIsComptimeModule ? BfPopulateType_Data : BfPopulateType_DataAndMethods);
  4456. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4457. if (mIsComptimeModule)
  4458. {
  4459. auto idVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, typeInstance->mTypeId);
  4460. return mBfIRBuilder->CreateIntToPtr(idVal, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4461. }
  4462. BfIRValue* globalVariablePtr = NULL;
  4463. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  4464. int numElements = 1;
  4465. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  4466. {
  4467. numElements += mCompiler->mMaxInterfaceSlots;
  4468. auto maxIFaceVirtIdx = 0;
  4469. if (!typeInstance->IsInterface())
  4470. {
  4471. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4472. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4473. numElements += typeInstance->GetOrigVTableSize();
  4474. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  4475. if (typeInstance->mHotTypeData != NULL)
  4476. {
  4477. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4478. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4479. }
  4480. numElements += ifaceMethodLen;
  4481. }
  4482. if (outNumElements != NULL)
  4483. *outNumElements = numElements;
  4484. }
  4485. StringT<128> classVDataName;
  4486. String memberName = "sBfClassVData";
  4487. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  4488. {
  4489. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  4490. memberName += "_";
  4491. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  4492. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  4493. }
  4494. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  4495. if (outMangledName != NULL)
  4496. *outMangledName = classVDataName;
  4497. /*if (itr != mClassVDataRefs.end())
  4498. {
  4499. globalVariable = itr->second;
  4500. }*/
  4501. BfIRValue globalVariable;
  4502. if (globalVariablePtr != NULL)
  4503. {
  4504. globalVariable = *globalVariablePtr;
  4505. }
  4506. else
  4507. {
  4508. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4509. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4510. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4511. arrayType,
  4512. true,
  4513. BfIRLinkageType_External,
  4514. BfIRValue(),
  4515. classVDataName);
  4516. mClassVDataRefs[typeInstance] = globalVariable;
  4517. }
  4518. return globalVariable;
  4519. }
  4520. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4521. {
  4522. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4523. if (mIsComptimeModule)
  4524. return mBfIRBuilder->Comptime_GetBfType(typeInstance->mTypeId, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4525. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4526. }
  4527. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4528. {
  4529. if (mBfIRBuilder->mIgnoreWrites)
  4530. return mBfIRBuilder->GetFakeVal();
  4531. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4532. BF_ASSERT(numElements >= 0);
  4533. if (numElements <= 0)
  4534. return BfIRValue();
  4535. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4536. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4537. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4538. BF_ASSERT(declTypeInst == implTypeInst);
  4539. else
  4540. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4541. if (declTypeInst != implTypeInst)
  4542. {
  4543. BfTypeInstance* highestImpl = declTypeInst;
  4544. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4545. {
  4546. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4547. break; // Start of an ext entry for another type
  4548. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4549. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4550. highestImpl = checkImplTypeInst;
  4551. }
  4552. if (highestImpl != implTypeInst)
  4553. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4554. }
  4555. BfVDataExtEntry mapEntry;
  4556. mapEntry.mDeclTypeInst = declTypeInst;
  4557. mapEntry.mImplTypeInst = implTypeInst;
  4558. BfIRValue* irValuePtr = NULL;
  4559. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4560. return *irValuePtr;
  4561. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4562. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4563. StringT<128> classVDataName;
  4564. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4565. if (declTypeInst != implTypeInst)
  4566. {
  4567. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4568. }
  4569. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4570. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4571. SizedArray<BfIRValue, 32> vData;
  4572. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4573. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4574. {
  4575. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4576. break; // Start of an ext entry for another type
  4577. BfIRValue vValue;
  4578. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4579. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4580. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4581. {
  4582. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4583. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4584. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4585. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4586. {
  4587. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4588. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4589. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4590. vValue = funcPtr;
  4591. }
  4592. }
  4593. if (!vValue)
  4594. vValue = voidPtrNull;
  4595. vData.Add(vValue);
  4596. }
  4597. BF_ASSERT((int)vData.size() == numElements);
  4598. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4599. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4600. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4601. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4602. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4603. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, vData);
  4604. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4605. mClassVDataExtRefs[mapEntry] = globalVariable;
  4606. return globalVariable;
  4607. }
  4608. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  4609. {
  4610. if (mBfIRBuilder->mIgnoreWrites)
  4611. {
  4612. return mBfIRBuilder->CreateTypeOf(type);
  4613. }
  4614. if (mIsComptimeModule)
  4615. {
  4616. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4617. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4618. return mBfIRBuilder->Comptime_GetReflectType(type->mTypeId, mBfIRBuilder->MapType(typeTypeInst));
  4619. }
  4620. PopulateType(type);
  4621. BfIRValue globalVariable;
  4622. BfIRValue* globalVariablePtr = NULL;
  4623. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  4624. {
  4625. if (*globalVariablePtr)
  4626. return mBfIRBuilder->CreateTypeOf(type, *globalVariablePtr);
  4627. }
  4628. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4629. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4630. auto typeInstance = type->ToTypeInstance();
  4631. StringT<128> typeDataName;
  4632. if (typeInstance != NULL)
  4633. {
  4634. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4635. }
  4636. else
  4637. {
  4638. typeDataName += "sBfTypeData.";
  4639. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  4640. }
  4641. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  4642. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  4643. mBfIRBuilder->SetReflectTypeData(mBfIRBuilder->MapType(type), globalVariable);
  4644. mTypeDataRefs[type] = globalVariable;
  4645. return mBfIRBuilder->CreateTypeOf(type, globalVariable);
  4646. }
  4647. void BfModule::EncodeAttributeData(BfTypeInstance* typeInstance, BfType* argType, BfIRValue arg, SizedArrayImpl<uint8>& data, Dictionary<int, int>& usedStringIdMap)
  4648. {
  4649. #define PUSH_INT8(val) data.push_back((uint8)val)
  4650. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4651. #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); }
  4652. #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); \
  4653. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4654. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4655. bool handled = false;
  4656. if (constant == NULL)
  4657. {
  4658. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  4659. return;
  4660. }
  4661. if (argType->IsObject())
  4662. {
  4663. if (argType->IsInstanceOf(mCompiler->mStringTypeDef))
  4664. {
  4665. int stringId = constant->mInt32;
  4666. int* orderedIdPtr;
  4667. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4668. {
  4669. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4670. }
  4671. GetStringObjectValue(stringId, true, true);
  4672. PUSH_INT8(0xFF); // String
  4673. PUSH_INT32(*orderedIdPtr);
  4674. return;
  4675. }
  4676. }
  4677. if (argType->IsPointer())
  4678. {
  4679. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  4680. {
  4681. if (constant->mTypeCode == BfTypeCode_StringId)
  4682. {
  4683. int stringId = constant->mInt32;
  4684. int* orderedIdPtr;
  4685. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4686. {
  4687. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4688. }
  4689. GetStringObjectValue(stringId, true, true);
  4690. PUSH_INT8(0xFF); // String
  4691. PUSH_INT32(*orderedIdPtr);
  4692. return;
  4693. }
  4694. }
  4695. }
  4696. PUSH_INT8(constant->mTypeCode);
  4697. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4698. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4699. (constant->mTypeCode == BfTypeCode_Double))
  4700. {
  4701. PUSH_INT64(constant->mInt64);
  4702. }
  4703. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4704. (constant->mTypeCode == BfTypeCode_UInt32) ||
  4705. (constant->mTypeCode == BfTypeCode_Char32))
  4706. {
  4707. PUSH_INT32(constant->mInt32);
  4708. }
  4709. else if (constant->mTypeCode == BfTypeCode_Float)
  4710. {
  4711. float val = (float)constant->mDouble;
  4712. PUSH_INT32(*(int*)&val);
  4713. }
  4714. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4715. (constant->mTypeCode == BfTypeCode_UInt16) ||
  4716. (constant->mTypeCode == BfTypeCode_Char16))
  4717. {
  4718. PUSH_INT16(constant->mInt16);
  4719. }
  4720. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4721. (constant->mTypeCode == BfTypeCode_UInt8) ||
  4722. (constant->mTypeCode == BfTypeCode_Boolean) ||
  4723. (constant->mTypeCode == BfTypeCode_Char8))
  4724. {
  4725. PUSH_INT8(constant->mInt8);
  4726. }
  4727. else if (constant->mConstType == BfConstType_TypeOf)
  4728. {
  4729. auto typeOf = (BfTypeOf_Const*)constant;
  4730. PUSH_INT32(typeOf->mType->mTypeId);
  4731. }
  4732. else if (constant->mConstType == BfConstType_AggZero)
  4733. {
  4734. for (int i = 0; i < argType->mSize; i++)
  4735. data.Add(0);
  4736. }
  4737. // else if (constant->mConstType == BfConstType_Agg)
  4738. // {
  4739. // BF_ASSERT(argType->IsComposite());
  4740. // if (argType->IsSizedArray())
  4741. // {
  4742. // auto argSizedArrayType = (BfSizedArrayType*)argType;
  4743. // }
  4744. // else
  4745. // {
  4746. // auto argTypeInstance = argType->ToTypeInstance();
  4747. // }
  4748. // }
  4749. else
  4750. {
  4751. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  4752. }
  4753. }
  4754. BfIRValue BfModule::CreateFieldData(BfFieldInstance* fieldInstance, int customAttrIdx)
  4755. {
  4756. bool isComptimeArg = mBfIRBuilder->mIgnoreWrites;
  4757. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4758. auto typeInstance = fieldInstance->mOwner;
  4759. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  4760. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4761. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  4762. BfType* typeIdType = intType;
  4763. BfTypeInstance* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef)->ToTypeInstance();
  4764. BfIRValue emptyValueType = mBfIRBuilder->mIgnoreWrites ?
  4765. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>()) :
  4766. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>());
  4767. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, !mIsComptimeModule);
  4768. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  4769. int typeId = 0;
  4770. auto fieldType = fieldInstance->GetResolvedType();
  4771. if (fieldType->IsGenericParam())
  4772. {
  4773. //TODO:
  4774. }
  4775. else
  4776. typeId = fieldType->mTypeId;
  4777. BfFieldFlags fieldFlags = (BfFieldFlags)0;
  4778. if (fieldDef->mProtection == BfProtection_Protected)
  4779. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Protected);
  4780. if (fieldDef->mProtection == BfProtection_Public)
  4781. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Public);
  4782. if (fieldDef->mIsStatic)
  4783. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Static);
  4784. if (fieldDef->mIsConst)
  4785. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Const);
  4786. if (fieldDef->IsEnumCaseEntry())
  4787. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_EnumCase);
  4788. BfIRValue constValue;
  4789. BfIRValue constValue2;
  4790. if (fieldInstance->GetFieldDef()->mIsConst)
  4791. {
  4792. if (fieldInstance->mConstIdx != -1)
  4793. {
  4794. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4795. uint64 val = constant->mUInt64;
  4796. if (constant->mTypeCode == BfTypeCode_Float)
  4797. {
  4798. float f = (float)*(double*)&val;
  4799. val = *(uint32*)&f;
  4800. }
  4801. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  4802. if (is32Bit)
  4803. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val >> 32);
  4804. }
  4805. }
  4806. else if (fieldInstance->GetFieldDef()->mIsStatic)
  4807. {
  4808. BfTypedValue refVal;
  4809. if (!mIsComptimeModule) // This can create circular reference issues for a `Self` static
  4810. refVal = ReferenceStaticField(fieldInstance);
  4811. if (refVal.mValue.IsConst())
  4812. {
  4813. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  4814. if (constant->mConstType == BfConstType_GlobalVar)
  4815. {
  4816. auto globalVar = (BfGlobalVar*)constant;
  4817. if (globalVar->mName[0] == '#')
  4818. refVal = BfTypedValue();
  4819. }
  4820. }
  4821. if ((refVal.IsAddr()) && (!isComptimeArg))
  4822. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  4823. }
  4824. if (!constValue)
  4825. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  4826. BfIRValue result;
  4827. if (is32Bit)
  4828. {
  4829. if (!constValue2)
  4830. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  4831. SizedArray<BfIRValue, 8> fieldVals =
  4832. {
  4833. emptyValueType,
  4834. fieldNameConst, // mName
  4835. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4836. constValue, // mData
  4837. constValue2, // mDataHi
  4838. GetConstValue(fieldFlags, shortType), // mFlags
  4839. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  4840. };
  4841. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  4842. result = isComptimeArg ?
  4843. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  4844. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  4845. }
  4846. else
  4847. {
  4848. SizedArray<BfIRValue, 8> fieldVals =
  4849. {
  4850. emptyValueType,
  4851. fieldNameConst, // mName
  4852. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4853. constValue, // mData
  4854. GetConstValue(fieldFlags, shortType), // mFlags
  4855. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  4856. };
  4857. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  4858. result = isComptimeArg ?
  4859. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  4860. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  4861. }
  4862. return result;
  4863. }
  4864. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  4865. {
  4866. if ((IsHotCompile()) && (!type->mDirty))
  4867. return BfIRValue();
  4868. BfIRValue* irValuePtr = NULL;
  4869. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  4870. {
  4871. return *irValuePtr;
  4872. }
  4873. BfTypeInstance* typeInstance = type->ToTypeInstance();
  4874. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  4875. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  4876. if (typeInstanceType == NULL)
  4877. {
  4878. AssertErrorState();
  4879. return BfIRValue();
  4880. }
  4881. BfIRValue typeTypeData;
  4882. int typeFlags = 0;
  4883. if (needsTypeData)
  4884. {
  4885. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  4886. BfTypeInstance* typeDataSource = NULL;
  4887. if (typeInstance != NULL)
  4888. {
  4889. if (typeInstance->IsUnspecializedType())
  4890. {
  4891. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  4892. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  4893. }
  4894. else if (typeInstance->IsArray())
  4895. {
  4896. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  4897. typeFlags |= BfTypeFlags_Array;
  4898. }
  4899. else if (typeInstance->IsGenericTypeInstance())
  4900. {
  4901. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  4902. typeFlags |= BfTypeFlags_SpecializedGeneric;
  4903. }
  4904. else
  4905. typeDataSource = typeInstanceTypeInstance;
  4906. }
  4907. else if (type->IsPointer())
  4908. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  4909. else if (type->IsRef())
  4910. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  4911. else if (type->IsSizedArray())
  4912. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  4913. else if (type->IsConstExprValue())
  4914. typeDataSource = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  4915. else if (type->IsGenericParam())
  4916. {
  4917. typeFlags |= BfTypeFlags_GenericParam;
  4918. typeDataSource = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  4919. }
  4920. else
  4921. typeDataSource = mContext->mBfTypeType;
  4922. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type) && (!mIsComptimeModule))
  4923. {
  4924. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  4925. }
  4926. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  4927. }
  4928. else
  4929. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  4930. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  4931. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  4932. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4933. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  4934. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  4935. BfType* typeIdType = intType;
  4936. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4937. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4938. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  4939. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4940. SizedArray<BfIRValue, 4> typeValueParams;
  4941. GetConstClassValueParam(typeTypeData, typeValueParams);
  4942. FixConstValueParams(mContext->mBfObjectType, typeValueParams);
  4943. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  4944. StringT<128> typeDataName;
  4945. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  4946. {
  4947. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4948. if (typeInstance->mTypeDef->IsGlobalsContainer())
  4949. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  4950. }
  4951. else
  4952. {
  4953. typeDataName += "sBfTypeData.";
  4954. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  4955. }
  4956. int typeCode = BfTypeCode_None;
  4957. if (typeInstance != NULL)
  4958. {
  4959. BF_ASSERT((type->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || mIsComptimeModule);
  4960. typeCode = typeInstance->mTypeDef->mTypeCode;
  4961. }
  4962. else if (type->IsPrimitiveType())
  4963. {
  4964. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  4965. typeCode = primType->mTypeDef->mTypeCode;
  4966. }
  4967. else if (type->IsPointer())
  4968. {
  4969. typeCode = BfTypeCode_Pointer;
  4970. typeFlags |= BfTypeFlags_Pointer;
  4971. }
  4972. else if (type->IsRef())
  4973. {
  4974. typeCode = BfTypeCode_Pointer;
  4975. typeFlags |= BfTypeFlags_Pointer;
  4976. }
  4977. if (type->IsObject())
  4978. {
  4979. typeFlags |= BfTypeFlags_Object;
  4980. if (typeInstance->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted)
  4981. {
  4982. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  4983. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  4984. typeFlags |= BfTypeFlags_HasDestructor;
  4985. }
  4986. }
  4987. if (type->IsStruct())
  4988. typeFlags |= BfTypeFlags_Struct;
  4989. if (type->IsInterface())
  4990. typeFlags |= BfTypeFlags_Interface;
  4991. if (type->IsBoxed())
  4992. {
  4993. typeFlags |= BfTypeFlags_Boxed;
  4994. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  4995. typeFlags |= BfTypeFlags_Pointer;
  4996. }
  4997. if (type->IsPrimitiveType())
  4998. typeFlags |= BfTypeFlags_Primitive;
  4999. if (type->IsTypedPrimitive())
  5000. typeFlags |= BfTypeFlags_TypedPrimitive;
  5001. if (type->IsTuple())
  5002. typeFlags |= BfTypeFlags_Tuple;
  5003. if (type->IsNullable())
  5004. typeFlags |= BfTypeFlags_Nullable;
  5005. if (type->IsSizedArray())
  5006. typeFlags |= BfTypeFlags_SizedArray;
  5007. if (type->IsConstExprValue())
  5008. typeFlags |= BfTypeFlags_ConstExpr;
  5009. if (type->IsSplattable())
  5010. typeFlags |= BfTypeFlags_Splattable;
  5011. if (type->IsUnion())
  5012. typeFlags |= BfTypeFlags_Union;
  5013. if (type->IsDelegate())
  5014. typeFlags |= BfTypeFlags_Delegate;
  5015. if (type->IsFunction())
  5016. typeFlags |= BfTypeFlags_Function;
  5017. if ((type->mDefineState != BfTypeDefineState_CETypeInit) && (type->WantsGCMarking()))
  5018. typeFlags |= BfTypeFlags_WantsMarking;
  5019. int virtSlotIdx = -1;
  5020. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5021. virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  5022. int memberDataOffset = 0;
  5023. if (type->IsInterface())
  5024. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  5025. else if (typeInstance != NULL)
  5026. {
  5027. for (auto& fieldInstance : typeInstance->mFieldInstances)
  5028. {
  5029. if (fieldInstance.mDataOffset != -1)
  5030. {
  5031. memberDataOffset = fieldInstance.mDataOffset;
  5032. break;
  5033. }
  5034. }
  5035. }
  5036. int boxedTypeId = 0;
  5037. if ((type->IsValueType()) || (type->IsWrappableType()))
  5038. {
  5039. auto boxedType = CreateBoxedType(type, false);
  5040. if ((boxedType != NULL) && (boxedType->mIsReified))
  5041. boxedTypeId = boxedType->mTypeId;
  5042. }
  5043. int stackCount = 0;
  5044. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  5045. {
  5046. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5047. if (typeOptions->mAllocStackTraceDepth != -1)
  5048. stackCount = BF_MIN(0xFF, BF_MAX(0x01, typeOptions->mAllocStackTraceDepth));
  5049. }
  5050. SizedArray<BfIRValue, 9> typeDataParams =
  5051. {
  5052. objectData,
  5053. GetConstValue(type->mSize, intType), // mSize
  5054. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5055. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  5056. GetConstValue(typeFlags, intType), // mTypeFlags
  5057. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  5058. GetConstValue(typeCode, byteType), // mTypeCode
  5059. GetConstValue(type->mAlign, byteType), // mAlign
  5060. GetConstValue(stackCount, byteType), // mAllocStackCountOverride
  5061. };
  5062. FixConstValueParams(mContext->mBfTypeType, typeDataParams);
  5063. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  5064. if (typeInstance == NULL)
  5065. {
  5066. BfIRValue typeDataVar;
  5067. if (needsTypeData)
  5068. {
  5069. if (type->IsPointer())
  5070. {
  5071. auto pointerType = (BfPointerType*)type;
  5072. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  5073. {
  5074. typeData,
  5075. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  5076. };
  5077. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5078. FixConstValueParams(reflectPointerType, pointerTypeDataParms);
  5079. auto pointerTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  5080. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  5081. BfIRLinkageType_External, pointerTypeData, typeDataName);
  5082. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5083. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5084. }
  5085. else if (type->IsRef())
  5086. {
  5087. auto refType = (BfRefType*)type;
  5088. SizedArray<BfIRValue, 3> refTypeDataParms =
  5089. {
  5090. typeData,
  5091. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  5092. GetConstValue((int8)refType->mRefKind, byteType),
  5093. };
  5094. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5095. FixConstValueParams(reflectRefType, refTypeDataParms);
  5096. auto refTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  5097. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  5098. BfIRLinkageType_External, refTypeData, typeDataName);
  5099. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5100. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5101. }
  5102. else if (type->IsSizedArray())
  5103. {
  5104. auto sizedArrayType = (BfSizedArrayType*)type;
  5105. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  5106. {
  5107. typeData,
  5108. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  5109. GetConstValue(sizedArrayType->mElementCount, intType)
  5110. };
  5111. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5112. FixConstValueParams(reflectSizedArrayType, sizedArrayTypeDataParms);
  5113. auto sizedArrayTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  5114. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  5115. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  5116. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5117. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5118. }
  5119. else if (type->IsConstExprValue())
  5120. {
  5121. auto constExprType = (BfConstExprValueType*)type;
  5122. SizedArray<BfIRValue, 3> constExprTypeDataParms =
  5123. {
  5124. typeData,
  5125. GetConstValue(constExprType->mType->mTypeId, typeIdType),
  5126. GetConstValue(constExprType->mValue.mInt64, longType)
  5127. };
  5128. auto reflectConstExprType = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5129. FixConstValueParams(reflectConstExprType, constExprTypeDataParms);
  5130. auto ConstExprTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectConstExprType, BfIRPopulateType_Full), constExprTypeDataParms);
  5131. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectConstExprType), true,
  5132. BfIRLinkageType_External, ConstExprTypeData, typeDataName);
  5133. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5134. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5135. }
  5136. else if (type->IsGenericParam())
  5137. {
  5138. auto genericParamType = (BfGenericParamType*)type;
  5139. SizedArray<BfIRValue, 3> genericParamTypeDataParms =
  5140. {
  5141. typeData
  5142. };
  5143. auto reflectGenericParamType = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5144. FixConstValueParams(reflectGenericParamType, genericParamTypeDataParms);
  5145. auto genericParamTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectGenericParamType, BfIRPopulateType_Full), genericParamTypeDataParms);
  5146. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectGenericParamType), true,
  5147. BfIRLinkageType_External, genericParamTypeData, typeDataName);
  5148. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5149. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5150. }
  5151. else
  5152. {
  5153. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  5154. BfIRLinkageType_External, typeData, typeDataName);
  5155. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5156. }
  5157. }
  5158. else
  5159. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5160. mTypeDataRefs[type] = typeDataVar;
  5161. return typeDataVar;
  5162. }
  5163. // Reserve position
  5164. mTypeDataRefs[typeInstance] = BfIRValue();
  5165. if ((typeInstance->IsReified()) && (!mIsComptimeModule))
  5166. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5167. BfTypeDef* typeDef = typeInstance->mTypeDef;
  5168. StringT<128> mangledName;
  5169. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  5170. if (!mIsComptimeModule)
  5171. {
  5172. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5173. {
  5174. auto methodDef = typeDef->mMethods[methodIdx];
  5175. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  5176. if (methodInstance == NULL)
  5177. continue;
  5178. if (typeInstance->IsUnspecializedType())
  5179. continue;
  5180. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5181. {
  5182. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  5183. {
  5184. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  5185. // We need to create an empty thunk for this chained method
  5186. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  5187. mBfIRBuilder->SetActiveFunction(func);
  5188. auto block = mBfIRBuilder->CreateBlock("entry", true);
  5189. mBfIRBuilder->SetInsertPoint(block);
  5190. mBfIRBuilder->CreateRetVoid();
  5191. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  5192. }
  5193. }
  5194. }
  5195. }
  5196. SizedArray<BfIRValue, 32> vData;
  5197. BfIRValue classVDataVar;
  5198. String classVDataName;
  5199. if (typeInstance->mSlotNum >= 0)
  5200. {
  5201. // For interfaces we ONLY emit the slot num
  5202. StringT<128> slotVarName;
  5203. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  5204. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  5205. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  5206. GetConstValue32(virtSlotIdx), slotVarName);
  5207. }
  5208. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  5209. {
  5210. int dynCastDataElems = 0;
  5211. int numElements = 1;
  5212. int vDataOfs = 1; // The number of intptrs before the iface slot map
  5213. numElements += mCompiler->mMaxInterfaceSlots;
  5214. if (!typeInstance->IsInterface())
  5215. {
  5216. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  5217. numElements += mCompiler->GetDynCastVDataCount();
  5218. numElements += typeInstance->mVirtualMethodTableSize;
  5219. }
  5220. int expectNumElements = 0;
  5221. if (!typeDef->mIsStatic)
  5222. {
  5223. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  5224. }
  5225. vData.push_back(BfIRValue()); // Type*
  5226. SizedArray<BfIRValue, 1> extVTableData;
  5227. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  5228. if (!typeInstance->IsInterface())
  5229. {
  5230. Array<int32> dynCastData;
  5231. if (typeInstance->IsBoxed())
  5232. {
  5233. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  5234. dynCastData.Add(underlyingType->mInheritanceId);
  5235. }
  5236. else
  5237. dynCastData.Add(typeInstance->mInheritanceId);
  5238. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  5239. dynCastData.Add(0);
  5240. dynCastData.Add(0);
  5241. auto checkTypeInst = typeInstance;
  5242. while (checkTypeInst != NULL)
  5243. {
  5244. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5245. {
  5246. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  5247. {
  5248. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  5249. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  5250. }
  5251. }
  5252. checkTypeInst = checkTypeInst->GetImplBaseType();
  5253. }
  5254. if (mSystem->mPtrSize == 8)
  5255. {
  5256. int intPtrCount = (dynCastDataElems + 1) / 2;
  5257. vDataOfs += intPtrCount;
  5258. uint64* intPtrData = (uint64*)&dynCastData[0];
  5259. for (int i = 0; i < intPtrCount; i++)
  5260. {
  5261. uint64 val = intPtrData[i];
  5262. if (val == 0)
  5263. {
  5264. vData.push_back(voidPtrNull);
  5265. }
  5266. else
  5267. {
  5268. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5269. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5270. }
  5271. }
  5272. }
  5273. else
  5274. {
  5275. int intPtrCount = dynCastDataElems;
  5276. vDataOfs += intPtrCount;
  5277. uint32* intPtrData = (uint32*)&dynCastData[0];
  5278. for (int i = 0; i < intPtrCount; i++)
  5279. {
  5280. uint32 val = intPtrData[i];
  5281. if (val == 0)
  5282. {
  5283. vData.push_back(voidPtrNull);
  5284. }
  5285. else
  5286. {
  5287. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  5288. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5289. }
  5290. }
  5291. }
  5292. }
  5293. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  5294. vData.push_back(voidPtrNull);
  5295. struct _InterfaceMatchEntry
  5296. {
  5297. BfTypeInterfaceEntry* mEntry;
  5298. BfTypeInstance* mEntrySource;
  5299. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  5300. };
  5301. int highestIFaceVirtIdx = 0;
  5302. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  5303. auto checkTypeInst = typeInstance;
  5304. bool forceInterfaceSet = false;
  5305. while (checkTypeInst != NULL)
  5306. {
  5307. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5308. {
  5309. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  5310. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject)))
  5311. continue;
  5312. _InterfaceMatchEntry* matchEntry = NULL;
  5313. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  5314. {
  5315. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  5316. if (compareCheckTypeInst->IsBoxed())
  5317. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  5318. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  5319. if (compareEntrySource->IsBoxed())
  5320. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  5321. auto prevEntry = matchEntry->mEntry;
  5322. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  5323. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  5324. if ((!isBetter) && (!isWorse))
  5325. {
  5326. // Unboxed comparison to Object fix
  5327. if (compareCheckTypeInst == mContext->mBfObjectType)
  5328. isWorse = true;
  5329. else if (compareEntrySource == mContext->mBfObjectType)
  5330. isBetter = true;
  5331. }
  5332. if (forceInterfaceSet)
  5333. {
  5334. isBetter = true;
  5335. isWorse = false;
  5336. }
  5337. if (isBetter == isWorse)
  5338. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  5339. if (isBetter == isWorse)
  5340. {
  5341. if (matchEntry->mAmbiguousEntries.empty())
  5342. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  5343. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  5344. continue;
  5345. }
  5346. else if (isBetter)
  5347. {
  5348. matchEntry->mEntry = &interfaceEntry;
  5349. matchEntry->mEntrySource = checkTypeInst;
  5350. matchEntry->mAmbiguousEntries.Clear();
  5351. }
  5352. else
  5353. continue;
  5354. }
  5355. else
  5356. {
  5357. _InterfaceMatchEntry matchEntry;
  5358. matchEntry.mEntry = &interfaceEntry;
  5359. matchEntry.mEntrySource = checkTypeInst;
  5360. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  5361. }
  5362. }
  5363. checkTypeInst = checkTypeInst->GetImplBaseType();
  5364. }
  5365. for (auto interfacePair : interfaceMap)
  5366. {
  5367. auto& interfaceMatchEntry = interfacePair.mValue;
  5368. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  5369. {
  5370. 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());
  5371. if (error != NULL)
  5372. {
  5373. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  5374. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  5375. }
  5376. }
  5377. }
  5378. if ((!mIsComptimeModule) && (!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  5379. {
  5380. int startTabIdx = (int)vData.size();
  5381. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  5382. BfTypeInstance* checkTypeInst = typeInstance;
  5383. while (checkTypeInst != NULL)
  5384. {
  5385. origVirtTypeStack.push_back(checkTypeInst);
  5386. checkTypeInst = checkTypeInst->GetImplBaseType();
  5387. }
  5388. Array<BfVirtualMethodEntry> origVTable;
  5389. int origVirtIdx = 0;
  5390. if (typeInstance->mTypeDef->mIsCombinedPartial)
  5391. {
  5392. HashSet<String> reslotNames;
  5393. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5394. {
  5395. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5396. if (entry.mDeclaringMethod.mMethodNum == -1)
  5397. continue;
  5398. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5399. if ((methodInstance == NULL) ||
  5400. ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))))
  5401. {
  5402. if (origVTable.empty())
  5403. origVTable = typeInstance->mVirtualMethodTable;
  5404. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  5405. if ((mIsComptimeModule) || (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject)))
  5406. {
  5407. // Prepare to reslot...
  5408. entry.mImplementingMethod = entry.mDeclaringMethod;
  5409. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  5410. }
  5411. else
  5412. {
  5413. // Decl isn't accessible, null out entry
  5414. entry.mImplementingMethod = BfMethodRef();
  5415. }
  5416. }
  5417. }
  5418. if (!reslotNames.IsEmpty())
  5419. {
  5420. BfAmbiguityContext ambiguityContext;
  5421. ambiguityContext.mTypeInstance = typeInstance;
  5422. ambiguityContext.mModule = this;
  5423. ambiguityContext.mIsProjectSpecific = true;
  5424. ambiguityContext.mIsReslotting = true;
  5425. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5426. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  5427. {
  5428. auto methodInstance = methodGroup.mDefault;
  5429. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  5430. continue;
  5431. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  5432. continue;
  5433. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  5434. continue;
  5435. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  5436. continue;
  5437. SlotVirtualMethod(methodInstance, &ambiguityContext);
  5438. }
  5439. ambiguityContext.Finish();
  5440. }
  5441. }
  5442. bool isInExts = false;
  5443. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5444. {
  5445. BfIRValue vValue = voidPtrNull;
  5446. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5447. BfModuleMethodInstance moduleMethodInst;
  5448. if (entry.mDeclaringMethod.mMethodNum == -1)
  5449. {
  5450. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  5451. isInExts = true;
  5452. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  5453. if (vExt)
  5454. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  5455. }
  5456. else
  5457. {
  5458. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  5459. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  5460. {
  5461. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  5462. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  5463. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5464. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5465. {
  5466. BF_ASSERT((mIsComptimeModule) || typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  5467. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5468. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5469. vValue = funcPtr;
  5470. }
  5471. }
  5472. }
  5473. while (origVirtTypeStack.size() != 0)
  5474. {
  5475. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  5476. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  5477. {
  5478. // Moved past current base vtable size
  5479. origVirtTypeStack.pop_back();
  5480. continue;
  5481. }
  5482. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  5483. {
  5484. // We are within the original vtable size
  5485. int idx = startTabIdx + origVirtIdx;
  5486. origVirtIdx++;
  5487. vData.push_back(vValue);
  5488. }
  5489. else
  5490. {
  5491. // This is a new entry, it only gets added to the ext
  5492. BF_ASSERT(isInExts);
  5493. }
  5494. break;
  5495. }
  5496. }
  5497. if (!origVTable.empty())
  5498. typeInstance->mVirtualMethodTable = origVTable;
  5499. }
  5500. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  5501. if (typeInstance->mHotTypeData != NULL)
  5502. {
  5503. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  5504. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  5505. }
  5506. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  5507. int iFaceMethodStartIdx = (int)vData.size();
  5508. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  5509. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  5510. vData[i] = voidPtrNull;
  5511. if (expectNumElements != 0)
  5512. BF_ASSERT(expectNumElements == vData.size());
  5513. //BF_ASSERT(vData.size() == expectNumElements);
  5514. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  5515. // ifaceMethodExtData.Add(voidPtrNull);
  5516. int ifaceEntryIdx = iFaceMethodStartIdx;
  5517. for (auto& interfacePair : interfaceMap)
  5518. {
  5519. auto interfaceEntry = interfacePair.mValue.mEntry;
  5520. if (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  5521. {
  5522. BF_ASSERT(mIsComptimeModule);
  5523. break;
  5524. }
  5525. bool makeEmpty = false;
  5526. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject)))
  5527. makeEmpty = true;
  5528. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5529. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  5530. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5531. {
  5532. BfIRValue pushValue;
  5533. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5534. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5535. continue;
  5536. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5537. continue;
  5538. if (makeEmpty)
  5539. {
  5540. pushValue = voidPtrNull;
  5541. }
  5542. else
  5543. {
  5544. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5545. auto methodInstance = (BfMethodInstance*)methodRef;
  5546. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5547. {
  5548. BF_ASSERT(methodInstance->mIsReified);
  5549. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5550. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5551. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5552. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5553. pushValue = funcPtr;
  5554. }
  5555. else
  5556. {
  5557. pushValue = voidPtrNull;
  5558. }
  5559. }
  5560. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5561. if (idx < ifaceMethodExtStart)
  5562. {
  5563. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  5564. vData[iFaceMethodStartIdx + idx] = pushValue;
  5565. }
  5566. else
  5567. {
  5568. BF_ASSERT(useExt);
  5569. int extIdx = idx - ifaceMethodExtStart;
  5570. while (extIdx >= ifaceMethodExtData.size())
  5571. ifaceMethodExtData.Add(voidPtrNull);
  5572. ifaceMethodExtData[extIdx] = pushValue;
  5573. }
  5574. }
  5575. }
  5576. if (typeInstance->IsBoxed())
  5577. {
  5578. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  5579. if (boxedType->IsBoxedStructPtr())
  5580. {
  5581. // Force override of GetHashCode so we use the pointer address as the hash code
  5582. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  5583. // Force override of GetHashCode so we use the pointer address as the hash code
  5584. for (auto& checkIFace : checkTypeInst->mInterfaces)
  5585. {
  5586. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5587. {
  5588. BfIRValue pushValue;
  5589. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5590. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5591. continue;
  5592. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5593. continue;
  5594. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5595. auto methodInstance = (BfMethodInstance*)methodRef;
  5596. BF_ASSERT(methodInstance->mIsReified);
  5597. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5598. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5599. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5600. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5601. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5602. vData[iFaceMethodStartIdx + idx] = funcPtr;
  5603. }
  5604. }
  5605. }
  5606. }
  5607. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic) && (!mIsComptimeModule))
  5608. {
  5609. BfIRValue ifaceMethodExtVar;
  5610. if ((!ifaceMethodExtData.IsEmpty()) && (!mIsComptimeModule))
  5611. {
  5612. StringT<128> classVDataName;
  5613. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  5614. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  5615. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  5616. BfIRLinkageType_External, BfIRValue(), classVDataName);
  5617. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  5618. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, ifaceMethodExtData);
  5619. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  5620. }
  5621. for (auto& ifaceInstPair : interfaceMap)
  5622. {
  5623. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  5624. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  5625. if (slotNum >= 0)
  5626. {
  5627. BfIRValue vtablePtr;
  5628. int idx = interfaceEntry->mStartVirtualIdx;
  5629. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5630. if ((endVirtualIdx > ifaceMethodExtStart) && (ifaceMethodExtVar))
  5631. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  5632. else
  5633. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  5634. int slotVirtIdx = slotNum + vDataOfs;
  5635. if (vData[slotVirtIdx] == voidPtrNull)
  5636. {
  5637. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  5638. }
  5639. else
  5640. {
  5641. if (mCompiler->IsHotCompile())
  5642. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  5643. else
  5644. Fail("Interface slot collision error", typeDef->GetRefNode());
  5645. }
  5646. }
  5647. }
  5648. }
  5649. }
  5650. BfIRValue typeNameConst;
  5651. BfIRValue namespaceConst;
  5652. if (needsTypeNames)
  5653. {
  5654. typeNameConst = GetStringObjectValue(typeDef->mName->mString, !mIsComptimeModule);
  5655. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), !mIsComptimeModule);
  5656. }
  5657. else
  5658. {
  5659. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  5660. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5661. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5662. }
  5663. int baseTypeId = 0;
  5664. if (typeInstance->mBaseType != NULL)
  5665. {
  5666. baseTypeId = typeInstance->mBaseType->mTypeId;
  5667. }
  5668. BfTypeOptions* typeOptions = NULL;
  5669. if (typeInstance->mTypeOptionsIdx >= 0)
  5670. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5671. SizedArray<BfIRValue, 16> customAttrs;
  5672. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  5673. BfIRValue castedClassVData;
  5674. if (classVDataVar)
  5675. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  5676. else
  5677. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  5678. bool freflectIncludeTypeData = false;
  5679. bool reflectIncludeAllFields = false;
  5680. bool reflectIncludeAllMethods = false;
  5681. if (TypeIsSubTypeOf(typeInstance, attributeType))
  5682. {
  5683. reflectIncludeAllFields = true;
  5684. reflectIncludeAllMethods = true;
  5685. }
  5686. BfReflectKind reflectKind = BfReflectKind_Type;
  5687. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  5688. {
  5689. BfReflectKind reflectKind = BfReflectKind_None;
  5690. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  5691. if (customAttrs != NULL)
  5692. {
  5693. for (auto& attr : customAttrs->mAttributes)
  5694. {
  5695. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  5696. }
  5697. delete customAttrs;
  5698. }
  5699. return reflectKind;
  5700. };
  5701. reflectKind = GetReflectKind(reflectKind, typeInstance);
  5702. // Fields
  5703. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  5704. BfIRValue emptyValueType = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  5705. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  5706. {
  5707. if (customAttributes == NULL)
  5708. return -1;
  5709. Array<BfCustomAttribute*> reflectAttributes;
  5710. for (auto& attr : customAttributes->mAttributes)
  5711. {
  5712. bool wantAttribute = false;
  5713. if (attr.mType->mCustomAttributes != NULL)
  5714. {
  5715. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  5716. if (usageAttribute != NULL)
  5717. {
  5718. // Check for Flags arg
  5719. if (usageAttribute->mCtorArgs.size() < 2)
  5720. continue;
  5721. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  5722. if (constant == NULL)
  5723. continue;
  5724. if (constant->mTypeCode == BfTypeCode_Boolean)
  5725. continue;
  5726. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  5727. wantAttribute = true;
  5728. }
  5729. }
  5730. if ((wantAttribute) && (attr.mType->mIsReified))
  5731. {
  5732. reflectAttributes.Add(&attr);
  5733. }
  5734. }
  5735. if (reflectAttributes.size() == 0)
  5736. return -1;
  5737. #define PUSH_INT8(val) data.push_back((uint8)val)
  5738. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  5739. #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); }
  5740. SizedArray<uint8, 16> data;
  5741. int customAttrIdx = (int)customAttrs.size();
  5742. data.push_back((uint8)reflectAttributes.size());
  5743. for (auto attr : reflectAttributes)
  5744. {
  5745. // Size prefix
  5746. int sizeIdx = (int)data.size();
  5747. PUSH_INT16(0); // mSize
  5748. PUSH_INT32(attr->mType->mTypeId); // mType
  5749. int ctorIdx = -1;
  5750. int ctorCount = 0;
  5751. attr->mType->mTypeDef->PopulateMemberSets();
  5752. BfMemberSetEntry* entry;
  5753. if (attr->mType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  5754. {
  5755. BfMethodDef* nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5756. while (nextMethodDef != NULL)
  5757. {
  5758. if (nextMethodDef == attr->mCtor)
  5759. ctorIdx = ctorCount;
  5760. nextMethodDef = nextMethodDef->mNextWithSameName;
  5761. ctorCount++;
  5762. }
  5763. }
  5764. BF_ASSERT(ctorIdx != -1);
  5765. if (ctorIdx != -1)
  5766. ctorIdx = (ctorCount - 1) - ctorIdx;
  5767. PUSH_INT16(ctorIdx);
  5768. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  5769. int argIdx = 0;
  5770. for (auto arg : attr->mCtorArgs)
  5771. {
  5772. auto argType = ctorMethodInstance->GetParamType(argIdx);
  5773. EncodeAttributeData(typeInstance, argType, arg, data, usedStringIdMap);
  5774. argIdx++;
  5775. }
  5776. int size = (int)data.size() - sizeIdx;
  5777. *((uint16*)&data[sizeIdx]) = size;
  5778. }
  5779. #undef PUSH_INT8
  5780. #undef PUSH_INT16
  5781. #undef PUSH_INT32
  5782. SizedArray<BfIRValue, 16> dataValues;
  5783. for (uint8 val : data)
  5784. dataValues.push_back(GetConstValue8(val));
  5785. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  5786. auto customAttrConst = mBfIRBuilder->CreateConstAgg_Value(dataArrayType, dataValues);
  5787. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  5788. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  5789. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  5790. customAttrs.push_back(customAttrArrayPtr);
  5791. return customAttrIdx;
  5792. };
  5793. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  5794. SizedArray<int, 16> reflectFieldIndices;
  5795. for (int pass = 0; pass < 2; pass++)
  5796. {
  5797. bool skippedField = false;
  5798. reflectFieldIndices.clear();
  5799. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  5800. {
  5801. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5802. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5803. if (fieldDef == NULL)
  5804. continue;
  5805. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  5806. bool includeField = reflectIncludeAllFields;
  5807. if (fieldInstance->mCustomAttributes != NULL)
  5808. {
  5809. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  5810. {
  5811. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  5812. {
  5813. includeField = true;
  5814. }
  5815. else
  5816. {
  5817. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  5818. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  5819. }
  5820. }
  5821. }
  5822. if ((fieldReflectKind & BfReflectKind_User) != 0)
  5823. includeField = true;
  5824. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  5825. includeField = true;
  5826. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  5827. includeField = true;
  5828. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  5829. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  5830. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  5831. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  5832. includeField |= forceReflectFields;
  5833. if (!includeField)
  5834. {
  5835. skippedField = true;
  5836. continue;
  5837. }
  5838. reflectFieldIndices.Add(fieldIdx);
  5839. }
  5840. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  5841. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  5842. // possible because we write out a SplatData structure containing just TypeIds in that case
  5843. if (pass == 0)
  5844. {
  5845. if (!typeInstance->IsSplattable())
  5846. break;
  5847. if (!skippedField)
  5848. break;
  5849. if (reflectFieldIndices.size() == 0)
  5850. break;
  5851. }
  5852. }
  5853. SizedArray<BfIRValue, 16> fieldTypes;
  5854. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  5855. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  5856. {
  5857. BfType* payloadType = typeInstance->GetUnionInnerType();
  5858. if (!payloadType->IsValuelessType())
  5859. {
  5860. BfIRValue payloadNameConst = GetStringObjectValue("$payload", !mIsComptimeModule);
  5861. SizedArray<BfIRValue, 8> payloadFieldVals;
  5862. if (is32Bit)
  5863. {
  5864. payloadFieldVals =
  5865. {
  5866. emptyValueType,
  5867. payloadNameConst, // mName
  5868. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  5869. GetConstValue(0, intPtrType), // mData
  5870. GetConstValue(0, intPtrType), // mDataHi
  5871. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  5872. GetConstValue(-1, intType), // mCustomAttributesIdx
  5873. };
  5874. }
  5875. else
  5876. {
  5877. payloadFieldVals =
  5878. {
  5879. emptyValueType,
  5880. payloadNameConst, // mName
  5881. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  5882. GetConstValue(0, intPtrType), // mData
  5883. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  5884. GetConstValue(-1, intType), // mCustomAttributesIdx
  5885. };
  5886. }
  5887. FixConstValueParams(reflectFieldDataType->ToTypeInstance(), payloadFieldVals);
  5888. auto payloadFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  5889. fieldTypes.push_back(payloadFieldData);
  5890. }
  5891. BfType* dscrType = typeInstance->GetDiscriminatorType();
  5892. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", !mIsComptimeModule);
  5893. SizedArray<BfIRValue, 8> dscrFieldVals;
  5894. if (is32Bit)
  5895. {
  5896. dscrFieldVals =
  5897. {
  5898. emptyValueType,
  5899. dscrNameConst, // mName
  5900. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  5901. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  5902. GetConstValue(0, intPtrType), // mDataHi
  5903. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  5904. GetConstValue(-1, intType), // mCustomAttributesIdx
  5905. };
  5906. }
  5907. else
  5908. {
  5909. dscrFieldVals =
  5910. {
  5911. emptyValueType,
  5912. dscrNameConst, // mName
  5913. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  5914. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  5915. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  5916. GetConstValue(-1, intType), // mCustomAttributesIdx
  5917. };
  5918. }
  5919. auto dscrFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  5920. fieldTypes.push_back(dscrFieldData);
  5921. }
  5922. for (auto fieldIdx : reflectFieldIndices)
  5923. {
  5924. if (!needsTypeData)
  5925. break;
  5926. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5927. fieldTypes.push_back(CreateFieldData(fieldInstance, _HandleCustomAttrs(fieldInstance->mCustomAttributes)));
  5928. }
  5929. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  5930. BfIRValue fieldDataPtr;
  5931. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  5932. if (fieldTypes.size() == 0)
  5933. {
  5934. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  5935. {
  5936. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  5937. SizedArray<BfIRValue, 3> splatTypes;
  5938. SizedArray<BfIRValue, 3> splatOffsets;
  5939. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  5940. {
  5941. auto checkTypeInstance = checkType->ToTypeInstance();
  5942. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  5943. PopulateType(checkTypeInstance);
  5944. if (checkType->IsStruct())
  5945. {
  5946. int dataEnd = offset;
  5947. if (checkTypeInstance->mBaseType != NULL)
  5948. _CheckSplat(checkTypeInstance->mBaseType, offset);
  5949. if (checkTypeInstance->mIsUnion)
  5950. {
  5951. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  5952. _CheckSplat(unionInnerType, offset);
  5953. }
  5954. else
  5955. {
  5956. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  5957. {
  5958. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  5959. if (fieldInstance->mDataIdx >= 0)
  5960. {
  5961. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  5962. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  5963. }
  5964. }
  5965. }
  5966. if (checkTypeInstance->IsEnum())
  5967. {
  5968. // Add discriminator
  5969. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  5970. if (checkTypeInstance->mPacking > 0)
  5971. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  5972. _CheckSplat(dscrType, dataEnd);
  5973. }
  5974. }
  5975. else if (checkType->IsMethodRef())
  5976. {
  5977. // auto methodRefType = (BfMethodRefType*)checkType;
  5978. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  5979. // {
  5980. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  5981. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  5982. // else
  5983. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  5984. // }
  5985. }
  5986. else if (!checkType->IsValuelessType())
  5987. {
  5988. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  5989. splatOffsets.Add(GetConstValue(offset, intType));
  5990. }
  5991. };
  5992. _CheckSplat(type, 0);
  5993. while (splatTypes.size() < 3)
  5994. {
  5995. splatTypes.Add(GetConstValue(0, typeIdType));
  5996. splatOffsets.Add(GetConstValue(0, intType));
  5997. }
  5998. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  5999. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  6000. SizedArray<BfIRValue, 8> splatVals =
  6001. {
  6002. emptyValueType,
  6003. splatTypesConst,
  6004. splatOffsetsConst
  6005. };
  6006. auto fieldSplatData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  6007. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  6008. fieldSplatData, typeDataName + ".splats");
  6009. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6010. }
  6011. else
  6012. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  6013. }
  6014. else
  6015. {
  6016. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  6017. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstAgg_Value(fieldDataConstType, fieldTypes);
  6018. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  6019. fieldDataConst, "fields." + typeDataName);
  6020. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6021. }
  6022. /// Methods
  6023. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  6024. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  6025. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  6026. struct _SortedMethodInfo
  6027. {
  6028. BfMethodDef* mMethodDef;
  6029. BfMethodCustomAttributes* mMethodCustomAttributes;
  6030. };
  6031. Array<_SortedMethodInfo> sortedMethodList;
  6032. SizedArray<BfIRValue, 16> methodTypes;
  6033. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  6034. {
  6035. if (!needsTypeData)
  6036. break;
  6037. // Disable const method reflection info for now
  6038. if (mIsComptimeModule)
  6039. break;
  6040. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6041. if (!methodInstanceGroup->IsImplemented())
  6042. continue;
  6043. auto methodDef = typeDef->mMethods[methodIdx];
  6044. if (methodDef->mIsNoReflect)
  6045. continue;
  6046. if (methodDef->mHasComptime)
  6047. continue;
  6048. auto defaultMethod = methodInstanceGroup->mDefault;
  6049. if (defaultMethod == NULL)
  6050. continue;
  6051. if (defaultMethod->mIsUnspecialized)
  6052. continue;
  6053. if (!defaultMethod->mIsReified)
  6054. continue;
  6055. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  6056. continue;
  6057. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  6058. continue;
  6059. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6060. bool includeMethod = reflectIncludeAllMethods;
  6061. BfMethodCustomAttributes* methodCustomAttributes = NULL;
  6062. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  6063. {
  6064. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes;
  6065. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  6066. {
  6067. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6068. {
  6069. includeMethod = true;
  6070. }
  6071. else
  6072. {
  6073. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6074. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  6075. }
  6076. }
  6077. }
  6078. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject)))
  6079. continue;
  6080. //
  6081. {
  6082. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  6083. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  6084. {
  6085. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  6086. {
  6087. if (paramDecl->mAttributes != NULL)
  6088. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  6089. }
  6090. }
  6091. }
  6092. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  6093. includeMethod = true;
  6094. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  6095. includeMethod = true;
  6096. if ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend))
  6097. {
  6098. if ((methodReflectKind & BfReflectKind_Constructors) != 0)
  6099. includeMethod = true;
  6100. if ((methodDef->IsDefaultCtor()) && ((methodReflectKind & BfReflectKind_DefaultConstructor) != 0))
  6101. includeMethod = true;
  6102. }
  6103. if ((!includeMethod) && (typeOptions != NULL))
  6104. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  6105. if (!includeMethod)
  6106. continue;
  6107. sortedMethodList.Add({ methodDef, methodCustomAttributes });
  6108. }
  6109. auto _GetMethodKind = [](BfMethodDef* methodDef)
  6110. {
  6111. if (methodDef->mMethodType == BfMethodType_Ctor)
  6112. return 0;
  6113. return 1;
  6114. };
  6115. std::sort(sortedMethodList.begin(), sortedMethodList.end(), [_GetMethodKind](const _SortedMethodInfo& lhs, const _SortedMethodInfo& rhs)
  6116. {
  6117. int lhsKind = _GetMethodKind(lhs.mMethodDef);
  6118. int rhsKind = _GetMethodKind(rhs.mMethodDef);
  6119. if (lhsKind != rhsKind)
  6120. return lhsKind < rhsKind;
  6121. if (lhs.mMethodDef->mName != rhs.mMethodDef->mName)
  6122. return lhs.mMethodDef->mName < rhs.mMethodDef->mName;
  6123. return lhs.mMethodDef->mIdx < rhs.mMethodDef->mIdx;
  6124. });
  6125. for (auto& methodInfo : sortedMethodList)
  6126. {
  6127. auto methodDef = methodInfo.mMethodDef;
  6128. int methodIdx = methodDef->mIdx;
  6129. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6130. auto defaultMethod = methodInstanceGroup->mDefault;
  6131. BfModuleMethodInstance moduleMethodInstance;
  6132. BfIRValue funcVal = voidPtrNull;
  6133. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  6134. (!typeInstance->IsUnspecializedType()) &&
  6135. (methodDef->mMethodType != BfMethodType_Ignore) &&
  6136. (methodDef->mMethodType != BfMethodType_Mixin) &&
  6137. (!methodDef->mIsAbstract) &&
  6138. (methodDef->mGenericParams.size() == 0))
  6139. {
  6140. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6141. if (moduleMethodInstance.mFunc)
  6142. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6143. }
  6144. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, !mIsComptimeModule);
  6145. BfMethodFlags methodFlags = defaultMethod->GetMethodFlags();
  6146. int customAttrIdx = -1;
  6147. int returnCustomAttrIdx = -1;
  6148. if (methodInfo.mMethodCustomAttributes != NULL)
  6149. {
  6150. customAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mCustomAttributes);
  6151. returnCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mReturnCustomAttributes);
  6152. }
  6153. enum ParamFlags
  6154. {
  6155. ParamFlag_None = 0,
  6156. ParamFlag_Splat = 1,
  6157. ParamFlag_Implicit = 2,
  6158. ParamFlag_AppendIdx = 4
  6159. };
  6160. SizedArray<BfIRValue, 8> paramVals;
  6161. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  6162. {
  6163. String paramName = defaultMethod->GetParamName(paramIdx);
  6164. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  6165. ParamFlags paramFlags = ParamFlag_None;
  6166. if (defaultMethod->GetParamIsSplat(paramIdx))
  6167. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  6168. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  6169. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Implicit | ParamFlag_AppendIdx);
  6170. BfIRValue paramNameConst = GetStringObjectValue(paramName, !mIsComptimeModule);
  6171. int paramCustomAttrIdx = -1;
  6172. if ((methodInfo.mMethodCustomAttributes != NULL) && (paramIdx < (int)methodInfo.mMethodCustomAttributes->mParamCustomAttributes.mSize))
  6173. paramCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mParamCustomAttributes[paramIdx]);
  6174. SizedArray<BfIRValue, 8> paramDataVals =
  6175. {
  6176. emptyValueType,
  6177. paramNameConst,
  6178. GetConstValue(paramType->mTypeId, typeIdType),
  6179. GetConstValue((int32)paramFlags, shortType),
  6180. GetConstValue(-1, intType), // defaultIdx
  6181. GetConstValue(paramCustomAttrIdx, intType) // customAttrIdx
  6182. };
  6183. auto paramData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  6184. paramVals.Add(paramData);
  6185. }
  6186. BfIRValue paramsVal;
  6187. if (paramVals.size() > 0)
  6188. {
  6189. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  6190. BfIRValue paramDataConst = mBfIRBuilder->CreateConstAgg_Value(paramDataArrayType, paramVals);
  6191. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  6192. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  6193. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  6194. }
  6195. else
  6196. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  6197. int vDataVal = -1;
  6198. if (defaultMethod->mVirtualTableIdx != -1)
  6199. {
  6200. int vDataIdx = -1;
  6201. if (type->IsInterface())
  6202. {
  6203. vDataIdx = defaultMethod->mVirtualTableIdx;
  6204. }
  6205. else
  6206. {
  6207. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  6208. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  6209. {
  6210. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  6211. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6212. if (extMethodIdx >= 0)
  6213. {
  6214. // Extension?
  6215. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6216. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  6217. }
  6218. else
  6219. {
  6220. // Map this new virtual index back to the original index
  6221. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  6222. }
  6223. }
  6224. else
  6225. {
  6226. vDataIdx += defaultMethod->mVirtualTableIdx;
  6227. }
  6228. }
  6229. if (vDataVal == -1)
  6230. vDataVal = vDataIdx * mSystem->mPtrSize;
  6231. }
  6232. SizedArray<BfIRValue, 8> methodDataVals =
  6233. {
  6234. emptyValueType,
  6235. methodNameConst, // mName
  6236. funcVal, // mFuncPtr
  6237. paramsVal,
  6238. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  6239. GetConstValue((int)paramVals.size(), shortType),
  6240. GetConstValue(methodFlags, shortType),
  6241. GetConstValue(methodIdx, intType),
  6242. GetConstValue(vDataVal, intType),
  6243. GetConstValue(customAttrIdx, intType),
  6244. GetConstValue(returnCustomAttrIdx, intType),
  6245. };
  6246. auto methodData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  6247. methodTypes.push_back(methodData);
  6248. }
  6249. BfIRValue methodDataPtr;
  6250. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  6251. if (methodTypes.size() == 0)
  6252. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  6253. else
  6254. {
  6255. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  6256. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methodTypes);
  6257. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6258. methodDataConst, "methods." + typeDataName);
  6259. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  6260. }
  6261. /////
  6262. int interfaceCount = 0;
  6263. BfIRValue interfaceDataPtr;
  6264. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  6265. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  6266. Array<bool> wantsIfaceMethod;
  6267. bool wantsIfaceMethods = false;
  6268. if (typeInstance->mInterfaces.IsEmpty())
  6269. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  6270. else
  6271. {
  6272. SizedArray<BfIRValue, 16> interfaces;
  6273. for (auto& interface : typeInstance->mInterfaces)
  6274. {
  6275. SizedArray<BfIRValue, 8> interfaceDataVals =
  6276. {
  6277. emptyValueType,
  6278. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  6279. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  6280. GetConstValue(interface.mStartVirtualIdx, intType),
  6281. };
  6282. auto interfaceData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  6283. interfaces.push_back(interfaceData);
  6284. if (!mIsComptimeModule)
  6285. {
  6286. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6287. {
  6288. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  6289. if (ifaceMethodGroup->mExplicitlyReflected)
  6290. {
  6291. wantsIfaceMethods = true;
  6292. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  6293. while (tableIdx >= wantsIfaceMethod.size())
  6294. wantsIfaceMethod.Add(false);
  6295. wantsIfaceMethod[tableIdx] = true;
  6296. }
  6297. }
  6298. }
  6299. }
  6300. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  6301. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstAgg_Value(interfaceDataArrayType, interfaces);
  6302. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  6303. interfaceDataConst, "interfaces." + typeDataName);
  6304. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  6305. interfaceCount = (int)interfaces.size();
  6306. }
  6307. BfIRValue interfaceMethodTable;
  6308. int ifaceMethodTableSize = 0;
  6309. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  6310. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  6311. {
  6312. SizedArray<BfIRValue, 16> methods;
  6313. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  6314. {
  6315. BfIRValue funcVal = voidPtrNull;
  6316. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  6317. {
  6318. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  6319. if (!methodEntry.mMethodRef.IsNull())
  6320. {
  6321. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  6322. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  6323. (!methodInstance->mMethodDef->mIsAbstract))
  6324. {
  6325. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  6326. if (moduleMethodInstance.mFunc)
  6327. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6328. }
  6329. }
  6330. }
  6331. methods.Add(funcVal);
  6332. }
  6333. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  6334. methods.pop_back();
  6335. if (!methods.IsEmpty())
  6336. {
  6337. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  6338. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methods);
  6339. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6340. methodDataConst, "imethods." + typeDataName);
  6341. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  6342. ifaceMethodTableSize = (int)methods.size();
  6343. }
  6344. }
  6345. if (!interfaceMethodTable)
  6346. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6347. /////
  6348. int underlyingType = 0;
  6349. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  6350. {
  6351. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  6352. }
  6353. int outerTypeId = 0;
  6354. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  6355. if (outerType != NULL)
  6356. {
  6357. outerTypeId = outerType->mTypeId;
  6358. }
  6359. //
  6360. BfIRValue customAttrDataPtr;
  6361. if (customAttrs.size() > 0)
  6362. {
  6363. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  6364. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstAgg_Value(customAttrsArrayType, customAttrs);
  6365. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  6366. customAttrsConst, "customAttrs." + typeDataName);
  6367. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  6368. }
  6369. else
  6370. {
  6371. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6372. }
  6373. SizedArray<BfIRValue, 32> typeDataVals =
  6374. {
  6375. typeData,
  6376. castedClassVData, // mTypeClassVData
  6377. typeNameConst, // mName
  6378. namespaceConst, // mNamespace
  6379. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  6380. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  6381. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  6382. GetConstValue(baseTypeId, typeIdType), // mBaseType
  6383. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  6384. GetConstValue(outerTypeId, typeIdType), // mOuterType
  6385. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  6386. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  6387. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  6388. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  6389. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  6390. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  6391. GetConstValue(0, shortType), // mPropertyDataCount
  6392. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  6393. interfaceDataPtr, // mInterfaceDataPtr
  6394. interfaceMethodTable, // mInterfaceMethodTable
  6395. methodDataPtr, // mMethodDataPtr
  6396. voidPtrNull, // mPropertyDataPtr
  6397. fieldDataPtr, // mFieldDataPtr
  6398. customAttrDataPtr, // mCustomAttrDataPtr
  6399. };
  6400. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  6401. FixConstValueParams(typeInstanceType->ToTypeInstance(), typeDataVals);
  6402. auto typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, typeDataVals);
  6403. if (!needsTypeData)
  6404. {
  6405. // No need for anything beyond typeInstanceData
  6406. }
  6407. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  6408. {
  6409. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6410. SizedArray<BfIRValue, 4> unspecializedData =
  6411. {
  6412. typeInstanceData,
  6413. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  6414. };
  6415. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  6416. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6417. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, unspecializedData);
  6418. }
  6419. else if (typeInstance->IsGenericTypeInstance())
  6420. {
  6421. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6422. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  6423. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef->GetDefinition());
  6424. SizedArray<BfIRValue, 4> resolvedTypes;
  6425. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  6426. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  6427. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  6428. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  6429. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  6430. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstAgg_Value(genericArrayType, resolvedTypes);
  6431. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  6432. resolvedTypesConst, "resolvedTypes." + typeDataName);
  6433. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  6434. SizedArray<BfIRValue, 3> specGenericData =
  6435. {
  6436. typeInstanceData,
  6437. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  6438. resovledTypesPtr, // mFieldDataPtr
  6439. };
  6440. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6441. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, specGenericData);
  6442. if (typeInstance->IsArray())
  6443. {
  6444. auto arrayType = (BfArrayType*)typeInstance;
  6445. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  6446. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  6447. SizedArray<BfIRValue, 4> arrayData =
  6448. {
  6449. typeInstanceData,
  6450. GetConstValue(elementType->mSize, intType), // mElementSize
  6451. GetConstValue(1, byteType), // mRank
  6452. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  6453. };
  6454. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  6455. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  6456. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, arrayData);
  6457. }
  6458. }
  6459. BfIRValue typeDataVar;
  6460. if (needsTypeData)
  6461. {
  6462. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  6463. BfIRLinkageType_External, typeInstanceData, typeDataName);
  6464. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  6465. if (mBfIRBuilder->DbgHasInfo())
  6466. {
  6467. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  6468. }
  6469. }
  6470. else
  6471. {
  6472. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  6473. }
  6474. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  6475. mTypeDataRefs[typeInstance] = typeDataVar;
  6476. if ((!mIsComptimeModule) && (classVDataVar))
  6477. {
  6478. BF_ASSERT(!classVDataName.IsEmpty());
  6479. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  6480. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  6481. auto classVDataConstData = mBfIRBuilder->CreateConstAgg_Value(classVDataConstDataType, vData);
  6482. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  6483. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6484. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  6485. else
  6486. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  6487. if (mBfIRBuilder->DbgHasInfo())
  6488. {
  6489. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6490. BfType* voidPtrType = CreatePointerType(voidType);
  6491. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6492. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  6493. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  6494. }
  6495. }
  6496. return typeDataVar;
  6497. }
  6498. BfIRValue BfModule::FixClassVData(BfIRValue value)
  6499. {
  6500. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  6501. return value;
  6502. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  6503. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  6504. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  6505. }
  6506. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  6507. {
  6508. // Note: this is not just for perf, it fixes a field var-type resolution issue
  6509. if (mBfIRBuilder->mIgnoreWrites)
  6510. return;
  6511. if (mIsComptimeModule)
  6512. return;
  6513. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  6514. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  6515. // When we access classes with static constructors FROM a static constructor,
  6516. // we call that other class's static constructor first. Recursion cannot occur, since
  6517. // we simply ignore subsequent attempts to re-enter the constructor
  6518. if (!typeInstance->mHasStaticInitMethod)
  6519. return;
  6520. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  6521. return;
  6522. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  6523. return;
  6524. auto checkTypeDef = typeInstance->mTypeDef;
  6525. checkTypeDef->PopulateMemberSets();
  6526. BfMethodDef* nextMethodDef = NULL;
  6527. BfMemberSetEntry* entry;
  6528. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  6529. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6530. while (nextMethodDef != NULL)
  6531. {
  6532. auto checkMethod = nextMethodDef;
  6533. nextMethodDef = nextMethodDef->mNextWithSameName;
  6534. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  6535. if (methodModule)
  6536. {
  6537. auto methodInstance = methodModule.mMethodInstance;
  6538. if ((methodInstance != NULL) &&
  6539. (methodInstance->mMethodDef->mIsStatic) &&
  6540. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  6541. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  6542. {
  6543. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  6544. break;
  6545. }
  6546. }
  6547. }
  6548. }
  6549. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  6550. {
  6551. auto methodOwner = methodInstance->GetOwner();
  6552. auto methodDef = methodInstance->mMethodDef;
  6553. auto methodDeclaration = methodDef->GetMethodDeclaration();
  6554. if (!methodDef->mIsExtern)
  6555. return BfIRFunction();
  6556. if (methodInstance->GetCustomAttributes() == NULL)
  6557. return BfIRFunction();
  6558. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  6559. {
  6560. String typeName = TypeToString(customAttribute.mType);
  6561. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  6562. {
  6563. methodInstance->mIsIntrinsic = true;
  6564. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  6565. String error;
  6566. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  6567. {
  6568. int stringId = constant->mInt32;
  6569. auto entry = mContext->mStringObjectIdMap[stringId];
  6570. String intrinName = entry.mString;
  6571. // if (intrinName.StartsWith(":"))
  6572. // {
  6573. // SizedArray<BfIRType, 2> paramTypes;
  6574. // for (auto& param : methodInstance->mParams)
  6575. // paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6576. // return mBfIRBuilder->GetIntrinsic(intrinName.Substring(1), mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6577. // }
  6578. // else
  6579. {
  6580. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  6581. if (intrinId != -1)
  6582. {
  6583. if (intrinId == BfIRIntrinsic_Malloc)
  6584. {
  6585. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6586. }
  6587. else if (intrinId == BfIRIntrinsic_Free)
  6588. {
  6589. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  6590. }
  6591. SizedArray<BfIRType, 2> paramTypes;
  6592. for (auto& param : methodInstance->mParams)
  6593. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6594. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6595. }
  6596. else if (reportFailure)
  6597. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  6598. }
  6599. }
  6600. else if (reportFailure)
  6601. error = "Intrinsic name must be a constant string";
  6602. if (reportFailure)
  6603. {
  6604. Fail(error, customAttribute.mRef);
  6605. }
  6606. }
  6607. }
  6608. return BfIRFunction();
  6609. }
  6610. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  6611. {
  6612. if (mBfIRBuilder->mIgnoreWrites)
  6613. return mBfIRBuilder->GetFakeFunction();
  6614. if (!mBuiltInFuncs[(int)funcTypeId])
  6615. {
  6616. SizedArray<BfIRType, 4> paramTypes;
  6617. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  6618. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6619. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  6620. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6621. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  6622. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  6623. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  6624. BfIRFunctionType funcType;
  6625. BfIRFunction func;
  6626. switch (funcTypeId)
  6627. {
  6628. case BfBuiltInFuncType_PrintF:
  6629. paramTypes.Add(nullPtrType);
  6630. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  6631. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  6632. break;
  6633. case BfBuiltInFuncType_Malloc:
  6634. {
  6635. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6636. {
  6637. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  6638. }
  6639. else
  6640. {
  6641. String funcName = mCompiler->mOptions.mMallocLinkName;
  6642. if (funcName.IsEmpty())
  6643. funcName = "malloc";
  6644. func = mBfIRBuilder->GetFunction(funcName);
  6645. if (!func)
  6646. {
  6647. paramTypes.clear();
  6648. paramTypes.push_back(intType);
  6649. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  6650. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6651. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  6652. }
  6653. }
  6654. }
  6655. break;
  6656. case BfBuiltInFuncType_Free:
  6657. {
  6658. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6659. {
  6660. func = GetInternalMethod("Dbg_RawFree").mFunc;
  6661. }
  6662. else
  6663. {
  6664. String funcName = mCompiler->mOptions.mFreeLinkName;
  6665. if (funcName.IsEmpty())
  6666. funcName = "free";
  6667. func = mBfIRBuilder->GetFunction(funcName);
  6668. if (!func)
  6669. {
  6670. paramTypes.clear();
  6671. paramTypes.push_back(nullPtrType);
  6672. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  6673. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6674. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  6675. }
  6676. }
  6677. }
  6678. break;
  6679. case BfBuiltInFuncType_LoadSharedLibraries:
  6680. paramTypes.clear();
  6681. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  6682. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  6683. break;
  6684. default: break;
  6685. }
  6686. mBuiltInFuncs[(int)funcTypeId] = func;
  6687. return func;
  6688. }
  6689. return mBuiltInFuncs[(int)funcTypeId];
  6690. }
  6691. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized, Array<BfTypeReference*>* deferredResolveTypes)
  6692. {
  6693. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  6694. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  6695. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  6696. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  6697. BfAutoComplete* bfAutocomplete = NULL;
  6698. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  6699. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  6700. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  6701. {
  6702. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  6703. {
  6704. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  6705. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  6706. {
  6707. String filter = nameNode->ToString();
  6708. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  6709. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  6710. if (nameIdx != 0)
  6711. {
  6712. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  6713. }
  6714. }
  6715. }
  6716. }
  6717. for (auto constraint : constraintDef->mConstraints)
  6718. {
  6719. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  6720. {
  6721. BfGenericOperatorConstraintInstance opConstraintInstance;
  6722. if (opConstraint->mLeftType != NULL)
  6723. {
  6724. if (bfAutocomplete != NULL)
  6725. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  6726. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces);
  6727. if (opConstraintInstance.mLeftType == NULL)
  6728. continue;
  6729. }
  6730. if (opConstraint->mRightType == NULL)
  6731. {
  6732. // We had a failure in parsing
  6733. continue;
  6734. }
  6735. if (opConstraint->mRightType != NULL)
  6736. {
  6737. if (bfAutocomplete != NULL)
  6738. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  6739. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces);
  6740. if (opConstraintInstance.mRightType == NULL)
  6741. continue;
  6742. }
  6743. if (opConstraint->mOpToken == NULL)
  6744. {
  6745. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  6746. continue;
  6747. }
  6748. if (opConstraint->mLeftType != NULL)
  6749. {
  6750. if (opConstraint->mRightType == NULL)
  6751. {
  6752. // Parse should have failed
  6753. continue;
  6754. }
  6755. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  6756. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  6757. {
  6758. Fail("Invalid binary operator", opConstraint->mOpToken);
  6759. continue;
  6760. }
  6761. }
  6762. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  6763. {
  6764. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  6765. }
  6766. else
  6767. {
  6768. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  6769. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  6770. {
  6771. Fail("Invalid unary operator", opConstraint->mOpToken);
  6772. continue;
  6773. }
  6774. }
  6775. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  6776. continue;
  6777. }
  6778. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  6779. if (bfAutocomplete != NULL)
  6780. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  6781. //TODO: Constraints may refer to other generic params (of either type or method)
  6782. // TO allow resolution, perhaps move this generic param initialization into GetMethodInstance (passing a genericPass bool)
  6783. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_AllowGenericMethodParamConstValue;
  6784. if (isUnspecialized)
  6785. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_DisallowComptime);
  6786. // We we have a deferredResolveTypes then we defer the generic validation, because we may have a case like
  6787. // `where T : Dictionay<TElem, int> and TElem : IHashable` and we don't want to throw the error on `T` before we build `TElem`
  6788. auto constraintType = ResolveTypeRef(constraintTypeRef, (deferredResolveTypes != NULL) ? BfPopulateType_Identity : BfPopulateType_Declaration, resolveFlags);
  6789. if (constraintType != NULL)
  6790. {
  6791. if (deferredResolveTypes != NULL)
  6792. {
  6793. PopulateType(constraintType, BfPopulateType_Declaration);
  6794. if (constraintType->IsUnspecializedTypeVariation())
  6795. deferredResolveTypes->Add(constraintTypeRef);
  6796. }
  6797. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6798. {
  6799. bool isValidTypeCode = false;
  6800. BfTypeCode typeCode = BfTypeCode_None;
  6801. if (constraintType->IsTypedPrimitive())
  6802. {
  6803. auto underlyingType = constraintType->GetUnderlyingType();
  6804. if (underlyingType->IsPrimitiveType())
  6805. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  6806. }
  6807. if (constraintType->IsPrimitiveType())
  6808. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  6809. if (constraintType->IsInstanceOf(mCompiler->mStringTypeDef))
  6810. isValidTypeCode = true;
  6811. switch (typeCode)
  6812. {
  6813. case BfTypeCode_StringId:
  6814. case BfTypeCode_Boolean:
  6815. case BfTypeCode_Int8:
  6816. case BfTypeCode_UInt8:
  6817. case BfTypeCode_Int16:
  6818. case BfTypeCode_UInt16:
  6819. case BfTypeCode_Int32:
  6820. case BfTypeCode_UInt32:
  6821. case BfTypeCode_Int64:
  6822. case BfTypeCode_UInt64:
  6823. case BfTypeCode_IntPtr:
  6824. case BfTypeCode_UIntPtr:
  6825. case BfTypeCode_IntUnknown:
  6826. case BfTypeCode_UIntUnknown:
  6827. case BfTypeCode_Float:
  6828. case BfTypeCode_Double:
  6829. case BfTypeCode_Char8:
  6830. case BfTypeCode_Char16:
  6831. case BfTypeCode_Char32:
  6832. isValidTypeCode = true;
  6833. break;
  6834. default: break;
  6835. }
  6836. if (isValidTypeCode)
  6837. {
  6838. genericParamInstance->mTypeConstraint = constraintType;
  6839. }
  6840. else
  6841. {
  6842. Fail("Const constraint must be a primitive type", constraintTypeRef);
  6843. }
  6844. }
  6845. else
  6846. {
  6847. bool checkEquality = false;
  6848. if (constraintType->IsVar())
  6849. {
  6850. // From a `comptype` generic undef resolution. Ignore.
  6851. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_ComptypeExpr);
  6852. genericParamInstance->mComptypeConstraint.Add(constraintTypeRef);
  6853. continue;
  6854. }
  6855. else if (constraintType->IsPrimitiveType())
  6856. {
  6857. if (isUnspecialized)
  6858. {
  6859. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  6860. continue;
  6861. }
  6862. checkEquality = true;
  6863. }
  6864. if (constraintType->IsArray())
  6865. {
  6866. if (isUnspecialized)
  6867. {
  6868. 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);
  6869. continue;
  6870. }
  6871. checkEquality = true;
  6872. }
  6873. if (constraintType->IsGenericParam())
  6874. {
  6875. checkEquality = true;
  6876. }
  6877. else if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  6878. {
  6879. if (isUnspecialized)
  6880. {
  6881. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  6882. continue;
  6883. }
  6884. checkEquality = true;
  6885. }
  6886. if (checkEquality)
  6887. {
  6888. genericParamInstance->mTypeConstraint = constraintType;
  6889. }
  6890. else if (constraintType->IsInterface())
  6891. {
  6892. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  6893. }
  6894. else
  6895. {
  6896. auto constraintTypeInst = constraintType->ToTypeInstance();
  6897. if (genericParamInstance->mTypeConstraint != NULL)
  6898. {
  6899. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  6900. {
  6901. // Allow more specific type
  6902. genericParamInstance->mTypeConstraint = constraintTypeInst;
  6903. }
  6904. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  6905. {
  6906. // Silently ignore less-specific type
  6907. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  6908. {
  6909. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  6910. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Class);
  6911. }
  6912. }
  6913. else
  6914. {
  6915. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  6916. return;
  6917. }
  6918. }
  6919. else
  6920. genericParamInstance->mTypeConstraint = constraintType;
  6921. }
  6922. }
  6923. }
  6924. }
  6925. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  6926. (genericParamInstance->mTypeConstraint == NULL))
  6927. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  6928. }
  6929. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  6930. {
  6931. if (genericParamSource.mMethodInstance != NULL)
  6932. {
  6933. //auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  6934. //SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  6935. return MethodToString(genericParamSource.mMethodInstance);
  6936. }
  6937. else
  6938. {
  6939. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  6940. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  6941. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  6942. return TypeToString(typeInst);
  6943. }
  6944. }
  6945. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  6946. {
  6947. Array<String> methodParamNameOverrides;
  6948. auto _TypeToString = [&](BfType* type)
  6949. {
  6950. if (genericParamSource.mMethodInstance != NULL)
  6951. {
  6952. if (methodParamNameOverrides.IsEmpty())
  6953. {
  6954. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  6955. methodParamNameOverrides.Add(genericParam->mName);
  6956. }
  6957. return TypeToString(type, &methodParamNameOverrides);
  6958. }
  6959. return TypeToString(type);
  6960. };
  6961. bool ignoreErrors = (errorOut == NULL) ||
  6962. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  6963. BfType* origCheckArgType = checkArgType;
  6964. if (origCheckArgType->IsRef())
  6965. origCheckArgType = origCheckArgType->GetUnderlyingType();
  6966. bool argIsReferenceType = false;
  6967. int checkGenericParamFlags = 0;
  6968. if (checkArgType->IsGenericParam())
  6969. {
  6970. BfGenericParamInstance* checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  6971. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  6972. if (checkGenericParamInst->mTypeConstraint != NULL)
  6973. checkArgType = checkGenericParamInst->mTypeConstraint;
  6974. // if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  6975. // {
  6976. // argMayBeReferenceType = false;
  6977. // }
  6978. // else
  6979. // {
  6980. // argMayBeReferenceType = true;
  6981. // }
  6982. }
  6983. if (checkArgType->IsObjectOrInterface())
  6984. argIsReferenceType = true;
  6985. BfTypeInstance* typeConstraintInst = NULL;
  6986. if (genericParamInst->mTypeConstraint != NULL)
  6987. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  6988. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  6989. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  6990. {
  6991. if ((!ignoreErrors) && (PreFail()))
  6992. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  6993. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6994. return false;
  6995. }
  6996. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  6997. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  6998. {
  6999. if ((!ignoreErrors) && (PreFail()))
  7000. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  7001. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7002. return false;
  7003. }
  7004. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  7005. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argIsReferenceType))
  7006. {
  7007. if ((!ignoreErrors) && (PreFail()))
  7008. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  7009. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7010. return false;
  7011. }
  7012. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum)
  7013. {
  7014. bool isEnum = checkArgType->IsEnum();
  7015. if ((origCheckArgType->IsGenericParam()) && (checkArgType->IsInstanceOf(mCompiler->mEnumTypeDef)))
  7016. isEnum = true;
  7017. if (((checkGenericParamFlags & (BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!isEnum))
  7018. {
  7019. if ((!ignoreErrors) && (PreFail()))
  7020. *errorOut = Fail(StrFormat("The type '%s' must be an enum type in order to use it as parameter '%s' for '%s'",
  7021. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7022. return false;
  7023. }
  7024. }
  7025. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) &&
  7026. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (checkArgType->IsInterface()))
  7027. {
  7028. if ((!ignoreErrors) && (PreFail()))
  7029. *errorOut = Fail(StrFormat("The type '%s' must be an concrete type in order to use it as parameter '%s' for '%s'",
  7030. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7031. return false;
  7032. }
  7033. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Interface) &&
  7034. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsInterface()))
  7035. {
  7036. if ((!ignoreErrors) && (PreFail()))
  7037. *errorOut = Fail(StrFormat("The type '%s' must be an interface type in order to use it as parameter '%s' for '%s'",
  7038. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7039. return false;
  7040. }
  7041. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7042. {
  7043. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  7044. {
  7045. if ((!ignoreErrors) && (PreFail()))
  7046. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  7047. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7048. return false;
  7049. }
  7050. }
  7051. else
  7052. {
  7053. if (checkArgType->IsConstExprValue())
  7054. {
  7055. if ((!ignoreErrors) && (PreFail()))
  7056. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  7057. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7058. return false;
  7059. }
  7060. }
  7061. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  7062. {
  7063. bool canDelete = false;
  7064. if (checkArgType->IsPointer())
  7065. canDelete = true;
  7066. else if (checkArgType->IsObjectOrInterface())
  7067. canDelete = true;
  7068. else if ((checkGenericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var)) != 0)
  7069. canDelete = true;
  7070. if (!canDelete)
  7071. {
  7072. if ((!ignoreErrors) && (PreFail()))
  7073. {
  7074. if (checkArgType->IsGenericParam())
  7075. *errorOut = Fail(StrFormat("Must add 'where %s : delete' constraint in order to use type as parameter '%s' for '%s'",
  7076. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7077. else
  7078. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  7079. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7080. }
  7081. return false;
  7082. }
  7083. }
  7084. if (checkArgType->IsPointer())
  7085. {
  7086. auto ptrType = (BfPointerType*)checkArgType;
  7087. checkArgType = ptrType->mElementType;
  7088. }
  7089. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  7090. {
  7091. bool canAlloc = false;
  7092. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  7093. {
  7094. if (checkTypeInst->IsObjectOrStruct())
  7095. {
  7096. checkTypeInst->mTypeDef->PopulateMemberSets();
  7097. BfMemberSetEntry* entry = NULL;
  7098. BfMethodDef* checkMethodDef = NULL;
  7099. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  7100. if (entry != NULL)
  7101. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  7102. bool hadProtected = false;
  7103. while (checkMethodDef != NULL)
  7104. {
  7105. if (!checkMethodDef->mParams.IsEmpty())
  7106. {
  7107. auto firstParam = checkMethodDef->mParams[0];
  7108. if (((firstParam->mParamKind == BfParamKind_Params) || (firstParam->mParamKind == BfParamKind_AppendIdx) || (firstParam->mParamKind == BfParamKind_VarArgs)) ||
  7109. ((firstParam->mParamDeclaration != NULL) && (firstParam->mParamDeclaration->mInitializer != NULL)))
  7110. {
  7111. // Allow all-default params
  7112. }
  7113. else
  7114. {
  7115. checkMethodDef = checkMethodDef->mNextWithSameName;
  7116. continue;
  7117. }
  7118. }
  7119. if (checkMethodDef->mProtection == BfProtection_Public)
  7120. {
  7121. canAlloc = true;
  7122. break;
  7123. }
  7124. if ((checkMethodDef->mProtection == BfProtection_Protected) || (checkMethodDef->mProtection == BfProtection_ProtectedInternal))
  7125. hadProtected = true;
  7126. checkMethodDef = checkMethodDef->mNextWithSameName;
  7127. }
  7128. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  7129. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  7130. }
  7131. }
  7132. else if (checkArgType->IsGenericParam())
  7133. {
  7134. canAlloc = (checkGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) != 0;
  7135. }
  7136. else if (checkArgType->IsPrimitiveType())
  7137. {
  7138. // Any primitive types and stuff can be allocated
  7139. canAlloc = true;
  7140. }
  7141. if (!canAlloc)
  7142. {
  7143. if ((!ignoreErrors) && (PreFail()))
  7144. {
  7145. if (checkArgType->IsGenericParam())
  7146. *errorOut = Fail(StrFormat("Must add 'where %s : new' constraint in order to use type as parameter '%s' for '%s'",
  7147. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7148. else
  7149. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  7150. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7151. }
  7152. return false;
  7153. }
  7154. }
  7155. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  7156. return true;
  7157. if (genericParamInst->mTypeConstraint != NULL)
  7158. {
  7159. bool constraintMatched = false;
  7160. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7161. {
  7162. if (checkArgType->IsConstExprValue())
  7163. {
  7164. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  7165. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  7166. {
  7167. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  7168. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  7169. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  7170. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  7171. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  7172. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  7173. {
  7174. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  7175. {
  7176. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7177. {
  7178. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue))
  7179. {
  7180. if ((!ignoreErrors) && (PreFail()))
  7181. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7182. constExprValueType->mValue.mInt64, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7183. return false;
  7184. }
  7185. }
  7186. else
  7187. {
  7188. if ((!ignoreErrors) && (PreFail()))
  7189. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with integer const '%lld', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7190. constExprValueType->mValue.mInt64, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7191. return false;
  7192. }
  7193. }
  7194. else
  7195. {
  7196. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7197. {
  7198. char valStr[64];
  7199. if (constExprValueType->mValue.mTypeCode == BfTypeCode_Double)
  7200. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  7201. else
  7202. ExactMinimalFloatToStr(constExprValueType->mValue.mSingle, valStr);
  7203. if ((!ignoreErrors) && (PreFail()))
  7204. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with floating point const '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7205. valStr, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7206. return false;
  7207. }
  7208. }
  7209. }
  7210. }
  7211. else if (genericParamInst->mTypeConstraint != constExprValueType->mType)
  7212. {
  7213. if ((!ignoreErrors) && (PreFail()))
  7214. *errorOut = Fail(StrFormat("Const generic argument '%s', declared as '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7215. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7216. return false;
  7217. }
  7218. }
  7219. }
  7220. else
  7221. {
  7222. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  7223. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  7224. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs);
  7225. if (convCheckConstraint == NULL)
  7226. return false;
  7227. if (((checkArgType->IsMethodRef()) || (checkArgType->IsFunction())) && (convCheckConstraint->IsDelegate()))
  7228. {
  7229. BfMethodInstance* checkMethodInstance;
  7230. if (checkArgType->IsMethodRef())
  7231. {
  7232. auto methodRefType = (BfMethodRefType*)checkArgType;
  7233. checkMethodInstance = methodRefType->mMethodRef;
  7234. }
  7235. else
  7236. {
  7237. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  7238. }
  7239. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  7240. BfExprEvaluator exprEvaluator(this);
  7241. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  7242. constraintMatched = true;
  7243. }
  7244. else if (CanCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  7245. {
  7246. constraintMatched = true;
  7247. }
  7248. else if (origCheckArgType->IsWrappableType())
  7249. {
  7250. if (origCheckArgType->IsSizedArray())
  7251. {
  7252. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  7253. if (convCheckConstraint->IsGenericTypeInstance())
  7254. {
  7255. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  7256. if (convCheckConstraintInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  7257. {
  7258. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  7259. {
  7260. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  7261. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  7262. constraintMatched = true;
  7263. }
  7264. }
  7265. }
  7266. }
  7267. if (!constraintMatched)
  7268. {
  7269. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7270. if (CanCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  7271. constraintMatched = true;
  7272. }
  7273. }
  7274. if (!constraintMatched)
  7275. {
  7276. if ((!ignoreErrors) && (PreFail()))
  7277. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  7278. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  7279. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  7280. return false;
  7281. }
  7282. }
  7283. }
  7284. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  7285. {
  7286. BfType* convCheckConstraint = checkConstraint;
  7287. if (convCheckConstraint->IsUnspecializedType())
  7288. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs);
  7289. if (convCheckConstraint == NULL)
  7290. return false;
  7291. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  7292. bool implementsInterface = false;
  7293. if (origCheckArgType != checkArgType)
  7294. {
  7295. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  7296. }
  7297. if (!implementsInterface)
  7298. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  7299. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  7300. {
  7301. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7302. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7303. implementsInterface = true;
  7304. }
  7305. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  7306. {
  7307. auto underlyingType = origCheckArgType->GetUnderlyingType();
  7308. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  7309. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7310. implementsInterface = true;
  7311. }
  7312. if (!implementsInterface)
  7313. {
  7314. if ((!ignoreErrors) && (PreFail()))
  7315. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  7316. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  7317. return false;
  7318. }
  7319. }
  7320. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  7321. {
  7322. auto leftType = checkOpConstraint.mLeftType;
  7323. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  7324. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs);
  7325. if (leftType != NULL)
  7326. leftType = FixIntUnknown(leftType);
  7327. auto rightType = checkOpConstraint.mRightType;
  7328. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  7329. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs);
  7330. if (rightType != NULL)
  7331. rightType = FixIntUnknown(rightType);
  7332. BfConstraintState constraintSet;
  7333. constraintSet.mPrevState = mContext->mCurConstraintState;
  7334. constraintSet.mGenericParamInstance = genericParamInst;
  7335. constraintSet.mLeftType = leftType;
  7336. constraintSet.mRightType = rightType;
  7337. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  7338. if (!CheckConstraintState(NULL))
  7339. return false;
  7340. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  7341. {
  7342. BfExprEvaluator exprEvaluator(this);
  7343. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  7344. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7345. //
  7346. {
  7347. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7348. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7349. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  7350. }
  7351. if ((!exprEvaluator.mResult) ||
  7352. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  7353. {
  7354. if ((!ignoreErrors) && (PreFail()))
  7355. {
  7356. if (genericParamInst->mExternType != NULL)
  7357. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  7358. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  7359. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7360. ), checkArgTypeRef);
  7361. else
  7362. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  7363. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7364. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7365. ), checkArgTypeRef);
  7366. }
  7367. return false;
  7368. }
  7369. }
  7370. else
  7371. {
  7372. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7373. StringT<128> failedOpName;
  7374. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  7375. {
  7376. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7377. failedOpName = "implicit conversion from '";
  7378. }
  7379. else
  7380. {
  7381. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7382. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7383. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  7384. {
  7385. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7386. failedOpName = "explicit conversion from '";
  7387. }
  7388. else
  7389. {
  7390. BfExprEvaluator exprEvaluator(this);
  7391. exprEvaluator.mResult = rightValue;
  7392. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  7393. if ((!exprEvaluator.mResult) ||
  7394. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  7395. {
  7396. failedOpName += "unary operation '";
  7397. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  7398. }
  7399. }
  7400. }
  7401. if (!failedOpName.IsEmpty())
  7402. {
  7403. if ((!ignoreErrors) && (PreFail()))
  7404. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  7405. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7406. failedOpName.c_str(), TypeToString(rightType).c_str()
  7407. ), checkArgTypeRef);
  7408. return false;
  7409. }
  7410. }
  7411. }
  7412. return true;
  7413. }
  7414. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  7415. {
  7416. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  7417. {
  7418. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  7419. return genericParamType;
  7420. }
  7421. auto genericParamType = new BfGenericParamType();
  7422. genericParamType->mContext = mContext;
  7423. genericParamType->mGenericParamKind = paramKind;
  7424. genericParamType->mGenericParamIdx = paramIdx;
  7425. PopulateType(genericParamType);
  7426. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  7427. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  7428. BfResolvedTypeSet::LookupContext lookupCtx;
  7429. lookupCtx.mModule = this;
  7430. BfResolvedTypeSet::Entry* typeEntry = NULL;
  7431. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  7432. BF_ASSERT(inserted);
  7433. typeEntry->mValue = genericParamType;
  7434. return genericParamType;
  7435. }
  7436. static int sValueFromExprIdx = 0;
  7437. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  7438. {
  7439. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  7440. if ((result) && (!ignoreNullable))
  7441. {
  7442. if (result.mType->IsVar())
  7443. return result;
  7444. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  7445. //TODO: Make this work, needed for 'void' and such
  7446. BfType* nullableType = NULL;
  7447. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  7448. {
  7449. BfTypeVector typeVec;
  7450. typeVec.push_back(result.mType);
  7451. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  7452. BF_ASSERT(nullableType != NULL);
  7453. }
  7454. // Go back to start and do any setup we need
  7455. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7456. BfTypedValue nullableTypedValue;
  7457. if (nullableType != NULL)
  7458. {
  7459. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  7460. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  7461. GetConstValue(nullableType->mSize), nullableType->mAlign);
  7462. }
  7463. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7464. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  7465. mBfIRBuilder->SetInsertPoint(notNullBB);
  7466. result = LoadValue(result);
  7467. if (nullableTypedValue)
  7468. {
  7469. auto elementType = nullableType->GetUnderlyingType();
  7470. if (elementType->IsVar())
  7471. {
  7472. // Do nothing
  7473. }
  7474. else if (elementType->IsValuelessType())
  7475. {
  7476. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  7477. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  7478. }
  7479. else
  7480. {
  7481. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  7482. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  7483. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  7484. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  7485. }
  7486. result = nullableTypedValue;
  7487. }
  7488. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7489. AddBasicBlock(pendingNullCond->mDoneBB);
  7490. if (nullableType == NULL)
  7491. {
  7492. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  7493. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  7494. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  7495. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  7496. {
  7497. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  7498. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  7499. }
  7500. result.mValue = phi;
  7501. }
  7502. }
  7503. else
  7504. {
  7505. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7506. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7507. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7508. AddBasicBlock(pendingNullCond->mDoneBB);
  7509. }
  7510. delete mCurMethodState->mPendingNullConditional;
  7511. mCurMethodState->mPendingNullConditional = NULL;
  7512. return result;
  7513. }
  7514. BF_NOINLINE void BfModule::EvaluateWithNewConditionalScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  7515. {
  7516. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  7517. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData);
  7518. if (mCurMethodState != NULL)
  7519. {
  7520. deferredLocalAssignData.mIsIfCondition = true;
  7521. deferredLocalAssignData.mIfMayBeSkipped = true;
  7522. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  7523. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  7524. mCurMethodState->mDeferredLocalAssignData = &deferredLocalAssignData;
  7525. }
  7526. BfScopeData newScope;
  7527. newScope.mOuterIsConditional = true;
  7528. newScope.mAllowTargeting = false;
  7529. if (mCurMethodState != NULL)
  7530. {
  7531. mCurMethodState->AddScope(&newScope);
  7532. NewScopeState(true, false);
  7533. }
  7534. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7535. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  7536. if (mCurMethodState != NULL)
  7537. RestoreScopeState();
  7538. }
  7539. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7540. {
  7541. //
  7542. {
  7543. BP_ZONE("CreateValueFromExpression:CheckStack");
  7544. StackHelper stackHelper;
  7545. if (!stackHelper.CanStackExpand(64 * 1024))
  7546. {
  7547. BfTypedValue result;
  7548. if (!stackHelper.Execute([&]()
  7549. {
  7550. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7551. }))
  7552. {
  7553. Fail("Expression too complex to compile", expr);
  7554. }
  7555. return result;
  7556. }
  7557. }
  7558. BP_ZONE("BfModule::CreateValueFromExpression");
  7559. if (outOrigType != NULL)
  7560. *outOrigType = NULL;
  7561. exprEvaluator.mExpectingType = wantTypeRef;
  7562. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7563. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  7564. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  7565. {
  7566. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope->mScopeKind != BfScopeKind_StatementTarget_Conditional))
  7567. {
  7568. EvaluateWithNewConditionalScope(exprEvaluator, expr, flags);
  7569. }
  7570. else
  7571. {
  7572. SetAndRestoreValue<bool> prevIsConditional(mCurMethodState->mCurScope->mIsConditional, true);
  7573. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7574. }
  7575. }
  7576. else
  7577. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7578. if (!exprEvaluator.mResult)
  7579. {
  7580. if ((flags & BfEvalExprFlags_InferReturnType) != 0)
  7581. return exprEvaluator.mResult;
  7582. if (!mCompiler->mPassInstance->HasFailed())
  7583. {
  7584. if (PreFail())
  7585. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  7586. }
  7587. return BfTypedValue();
  7588. }
  7589. auto typedVal = exprEvaluator.mResult;
  7590. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  7591. {
  7592. BF_ASSERT(typedVal.mType->IsGenericParam());
  7593. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  7594. bool handled = false;
  7595. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7596. {
  7597. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  7598. if (genericTypeConstraint != NULL)
  7599. {
  7600. auto underlyingConstraint = genericTypeConstraint;
  7601. if ((underlyingConstraint != NULL) && (underlyingConstraint->IsBoxed()))
  7602. underlyingConstraint = underlyingConstraint->GetUnderlyingType();
  7603. if (underlyingConstraint != NULL)
  7604. {
  7605. BfTypedValue result;
  7606. result.mKind = BfTypedValueKind_Value;
  7607. result.mType = genericTypeConstraint;
  7608. result.mValue = mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(underlyingConstraint));
  7609. typedVal = result;
  7610. handled = true;
  7611. }
  7612. }
  7613. }
  7614. if (!handled)
  7615. {
  7616. //Fail("Only const generic parameters can be used as values", expr);
  7617. AssertErrorState();
  7618. return BfTypedValue();
  7619. }
  7620. }
  7621. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  7622. FixIntUnknown(typedVal);
  7623. if (!mBfIRBuilder->mIgnoreWrites)
  7624. FixValueActualization(typedVal);
  7625. exprEvaluator.CheckResultForReading(typedVal);
  7626. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  7627. {
  7628. if ((flags & BfEvalExprFlags_NoCast) == 0)
  7629. {
  7630. // Only allow a 'ref' type if we have an explicit 'ref' operator
  7631. bool allowRef = false;
  7632. BfExpression* checkExpr = expr;
  7633. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  7634. checkExpr = parenExpr->mExpression;
  7635. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  7636. {
  7637. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  7638. allowRef = true;
  7639. }
  7640. if (!allowRef)
  7641. typedVal = RemoveRef(typedVal);
  7642. }
  7643. }
  7644. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  7645. {
  7646. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  7647. {
  7648. BF_ASSERT(!typedVal.mValue.IsFake());
  7649. }
  7650. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7651. }
  7652. if (wantTypeRef != NULL)
  7653. {
  7654. if (outOrigType != NULL)
  7655. *outOrigType = typedVal.mType;
  7656. if (((flags & BfEvalExprFlags_NoCast) == 0) && (!wantTypeRef->IsVar()))
  7657. {
  7658. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  7659. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  7660. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  7661. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  7662. if (!typedVal)
  7663. return typedVal;
  7664. }
  7665. if (exprEvaluator.mIsVolatileReference)
  7666. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7667. }
  7668. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  7669. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7670. return typedVal;
  7671. }
  7672. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7673. {
  7674. BfExprEvaluator exprEvaluator(this);
  7675. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7676. }
  7677. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  7678. {
  7679. BfExprEvaluator exprEvaluator(this);
  7680. exprEvaluator.Evaluate(expr);
  7681. if (!exprEvaluator.mResult)
  7682. {
  7683. Fail("Invalid expression type", expr);
  7684. return BfTypedValue();
  7685. }
  7686. if (!exprEvaluator.mResult.IsAddr())
  7687. {
  7688. Fail("Cannot assign to value", expr);
  7689. return BfTypedValue();
  7690. }
  7691. return exprEvaluator.mResult;
  7692. }
  7693. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  7694. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  7695. {
  7696. auto typeInstance = typedValue.mType->ToTypeInstance();
  7697. if (zeroMemory)
  7698. {
  7699. int zeroAlign = typedValue.mType->mAlign;
  7700. if (typeInstance != NULL)
  7701. zeroAlign = typeInstance->mInstAlign;
  7702. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  7703. }
  7704. if (!typedValue.mType->IsObject())
  7705. {
  7706. return;
  7707. }
  7708. if ((scopeData == NULL) && (mCurMethodState != NULL))
  7709. return; // Handled in heap alloc funcs
  7710. auto typeDef = typeInstance->mTypeDef;
  7711. mBfIRBuilder->PopulateType(typedValue.mType);
  7712. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  7713. bool isAutocomplete = mCompiler->IsAutocomplete();
  7714. BfIRValue vDataRef;
  7715. if (!isAutocomplete)
  7716. {
  7717. vDataRef = GetClassVDataPtr(typeInstance);
  7718. }
  7719. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  7720. auto ptrType = CreatePointerType(i8Type);
  7721. auto ptrPtrType = CreatePointerType(ptrType);
  7722. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  7723. PopulateType(ptrType, BfPopulateType_Declaration);
  7724. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  7725. if (!isAutocomplete)
  7726. {
  7727. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  7728. {
  7729. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7730. SizedArray<BfIRValue, 4> llvmArgs;
  7731. llvmArgs.push_back(objectPtr);
  7732. llvmArgs.push_back(vDataRef);
  7733. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  7734. if (objectStackInitMethod)
  7735. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  7736. }
  7737. else
  7738. {
  7739. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  7740. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  7741. mBfIRBuilder->CreateStore(srcVal, destAddr);
  7742. }
  7743. }
  7744. }
  7745. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  7746. {
  7747. BfIRValue result;
  7748. BfType* ptrType;
  7749. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  7750. ptrType = type;
  7751. else
  7752. ptrType = CreatePointerType(type);
  7753. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  7754. {
  7755. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7756. SizedArray<BfExpression*, 2> argExprs;
  7757. BfTypedValueExpression typedValueExpr;
  7758. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  7759. typedValueExpr.mRefNode = refNode;
  7760. argExprs.push_back(&typedValueExpr);
  7761. BfTypedValueExpression appendSizeValueExpr;
  7762. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  7763. appendSizeValueExpr.mRefNode = refNode;
  7764. argExprs.push_back(&appendSizeValueExpr);
  7765. BfExprEvaluator exprEvaluator(this);
  7766. BfTypedValue allocResult;
  7767. if (allocTarget.mScopedInvocationTarget != NULL)
  7768. {
  7769. SizedArray<BfTypeReference*, 2> genericArgs;
  7770. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, BfMethodGenericArguments());
  7771. allocResult = LoadValue(exprEvaluator.mResult);
  7772. }
  7773. else if (allocTarget.mCustomAllocator)
  7774. {
  7775. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  7776. if (customTypeInst == NULL)
  7777. {
  7778. if (allocTarget.mCustomAllocator.mType->IsStructPtr())
  7779. customTypeInst = allocTarget.mCustomAllocator.mType->GetUnderlyingType()->ToTypeInstance();
  7780. }
  7781. if (customTypeInst == NULL)
  7782. {
  7783. Fail(StrFormat("Type '%s' cannot be used as a custom allocator", TypeToString(allocTarget.mCustomAllocator.mType).c_str()), refNode);
  7784. }
  7785. else
  7786. {
  7787. BfTypedValueExpression typeValueExpr;
  7788. String allocMethodName = "Alloc";
  7789. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  7790. {
  7791. allocMethodName = "AllocTyped";
  7792. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  7793. auto typeRefVal = CreateTypeDataRef(type);
  7794. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  7795. typeValueExpr.mRefNode = refNode;
  7796. argExprs.Insert(0, &typeValueExpr);
  7797. }
  7798. if (HasMixin(customTypeInst, allocMethodName, 2))
  7799. {
  7800. BfSizedArray<BfExpression*> argExprArr;
  7801. argExprArr.mSize = (int)argExprs.size();
  7802. argExprArr.mVals = &argExprs[0];
  7803. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  7804. allocResult = exprEvaluator.GetResult();
  7805. }
  7806. else
  7807. {
  7808. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  7809. BfResolvedArgs argValues(&sizedArgExprs);
  7810. exprEvaluator.ResolveArgValues(argValues);
  7811. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  7812. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, BfMethodGenericArguments());
  7813. }
  7814. }
  7815. }
  7816. if (allocResult)
  7817. {
  7818. if (allocResult.mType->IsVoidPtr())
  7819. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  7820. else
  7821. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  7822. return result;
  7823. }
  7824. }
  7825. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  7826. return result;
  7827. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7828. {
  7829. BfIRValue allocData = GetDbgRawAllocData(type);
  7830. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  7831. SizedArray<BfIRValue, 2> llvmArgs;
  7832. llvmArgs.push_back(sizeValue);
  7833. llvmArgs.push_back(allocData);
  7834. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  7835. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  7836. }
  7837. BfModuleMethodInstance moduleMethodInstance;
  7838. moduleMethodInstance = GetInternalMethod("Malloc");
  7839. SizedArray<BfIRValue, 1> llvmArgs;
  7840. llvmArgs.push_back(sizeValue);
  7841. auto func = moduleMethodInstance.mFunc;
  7842. if ((!func) || (func.IsFake()))
  7843. {
  7844. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  7845. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  7846. }
  7847. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  7848. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  7849. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  7850. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  7851. return result;
  7852. }
  7853. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  7854. {
  7855. if (type->IsStruct())
  7856. {
  7857. auto typeInstance = type->ToTypeInstance();
  7858. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  7859. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7860. }
  7861. else if (type->IsObjectOrInterface())
  7862. {
  7863. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  7864. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  7865. BF_ASSERT(moduleMethodInst.mFunc);
  7866. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7867. }
  7868. else
  7869. {
  7870. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  7871. BfExprEvaluator exprEvaluator(this);
  7872. SizedArray<BfResolvedArg, 1> resolvedArgs;
  7873. BfResolvedArg resolvedArg;
  7874. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  7875. resolvedArgs.Add(resolvedArg);
  7876. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, BfMethodGenericArguments());
  7877. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  7878. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  7879. BF_ASSERT(moduleMethodInst.mFunc);
  7880. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7881. }
  7882. return BfIRValue();
  7883. }
  7884. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  7885. {
  7886. BfIRValue allocDataValue;
  7887. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  7888. return allocDataValue;
  7889. BfIRValue markFuncPtr;
  7890. if (type->WantsGCMarking())
  7891. markFuncPtr = GetMarkFuncPtr(type);
  7892. else
  7893. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7894. BfIRValue typeDataRef = CreateTypeDataRef(type);
  7895. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  7896. BfTypeInstance* typeInstance = type->ToTypeInstance();
  7897. if (typeInstance == NULL)
  7898. {
  7899. typeInstance = GetWrappedStructType(type);
  7900. if (typeInstance != NULL)
  7901. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  7902. }
  7903. if (typeInstance != NULL)
  7904. PopulateType(typeInstance);
  7905. int stackCount = mCompiler->mOptions.mAllocStackCount;
  7906. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  7907. {
  7908. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  7909. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  7910. }
  7911. SizedArray<BfIRValue, 2> dataValues;
  7912. dataValues.Add(mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  7913. dataValues.Add(typeDataRef);
  7914. dataValues.Add(markFuncPtr);
  7915. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  7916. BfIRValue dataStruct = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  7917. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  7918. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  7919. return allocDataValue;
  7920. }
  7921. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  7922. {
  7923. BP_ZONE("AllocFromType");
  7924. BfScopeData* scopeData = allocTarget.mScopeData;
  7925. BF_ASSERT(!type->IsVar());
  7926. auto typeInstance = type->ToTypeInstance();
  7927. if ((typeInstance == NULL) && (type->IsGenericParam()))
  7928. typeInstance = mContext->mBfObjectType;
  7929. bool isHeapAlloc = scopeData == NULL;
  7930. bool isScopeAlloc = scopeData != NULL;
  7931. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  7932. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  7933. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  7934. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  7935. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  7936. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  7937. {
  7938. BfPointerType* ptrType = CreatePointerType(type);
  7939. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  7940. return val;
  7941. }
  7942. if (typeInstance != NULL)
  7943. mBfIRBuilder->PopulateType(typeInstance);
  7944. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  7945. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  7946. {
  7947. return mBfIRBuilder->GetFakeVal();
  7948. }
  7949. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  7950. BfIRValue sizeValue;
  7951. BfIRType allocType = mBfIRBuilder->MapType(type);
  7952. int allocSize = type->mSize;
  7953. int allocAlign = type->mAlign;
  7954. if (typeInstance != NULL)
  7955. {
  7956. if (!mBfIRBuilder->mIgnoreWrites)
  7957. typeInstance->mHasBeenInstantiated = true;
  7958. allocSize = typeInstance->mInstSize;
  7959. allocAlign = typeInstance->mInstAlign;
  7960. //if (typeInstance->IsEnum())
  7961. //allocType = typeInstance->mIRType;
  7962. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  7963. }
  7964. if (alignOverride != -1)
  7965. allocAlign = alignOverride;
  7966. // The "dynSize" cases:
  7967. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  7968. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  7969. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  7970. // though we'd expect their stack space to be released
  7971. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  7972. {
  7973. MarkDynStack(scopeData);
  7974. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7975. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  7976. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  7977. BfType* voidPtrType = CreatePointerType(voidType);
  7978. if (!mCurMethodState->mDynStackRevIdx)
  7979. {
  7980. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  7981. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7982. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7983. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  7984. mBfIRBuilder->ClearDebugLocation(storeInst);
  7985. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7986. }
  7987. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  7988. auto bytePtrType = CreatePointerType(byteType);
  7989. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  7990. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  7991. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7992. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7993. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  7994. mBfIRBuilder->ClearDebugLocation(storeInst);
  7995. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  7996. mBfIRBuilder->ClearDebugLocation(storeInst);
  7997. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7998. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  7999. if (IsTargetingBeefBackend())
  8000. {
  8001. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  8002. // to ensure there isn't any register collision during looping is just to not allow it to
  8003. // bind to a register at all
  8004. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  8005. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  8006. }
  8007. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  8008. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  8009. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  8010. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  8011. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  8012. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  8013. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  8014. mBfIRBuilder->AddBlock(verCheckBB);
  8015. mBfIRBuilder->SetInsertPoint(verCheckBB);
  8016. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  8017. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  8018. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  8019. mBfIRBuilder->AddBlock(resizeBB);
  8020. mBfIRBuilder->SetInsertPoint(resizeBB);
  8021. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8022. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  8023. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  8024. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  8025. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  8026. mBfIRBuilder->CreateBr(endBB);
  8027. mBfIRBuilder->AddBlock(endBB);
  8028. mBfIRBuilder->SetInsertPoint(endBB);
  8029. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  8030. };
  8031. if (isScopeAlloc)
  8032. {
  8033. if (arraySize)
  8034. {
  8035. bool isConstantArraySize = arraySize.IsConst();
  8036. if (isRawArrayAlloc)
  8037. {
  8038. BfPointerType* ptrType = CreatePointerType(type);
  8039. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8040. {
  8041. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8042. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  8043. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  8044. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  8045. }
  8046. else
  8047. {
  8048. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8049. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  8050. if (!isDynAlloc)
  8051. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8052. else
  8053. {
  8054. MarkDynStack(scopeData);
  8055. SaveStackState(scopeData);
  8056. }
  8057. int typeSize = type->GetStride();
  8058. BfIRValue allocaInst;
  8059. BfIRValue result;
  8060. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  8061. {
  8062. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  8063. result = allocaInst;
  8064. }
  8065. else
  8066. {
  8067. if (typeInstance->IsStruct())
  8068. typeSize = typeInstance->GetInstStride();
  8069. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  8070. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  8071. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8072. auto ptrType = CreatePointerType(typeInstance);
  8073. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  8074. if (!isDynAlloc)
  8075. mBfIRBuilder->ClearDebugLocation(result);
  8076. }
  8077. if (!isDynAlloc)
  8078. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8079. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8080. if (!isDynAlloc)
  8081. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8082. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  8083. if (arraySize.IsConst())
  8084. {
  8085. auto constant = mBfIRBuilder->GetConstant(arraySize);
  8086. if (constant->mInt64 == 0)
  8087. noDtorCall = true;
  8088. }
  8089. if (!noDtorCall)
  8090. {
  8091. bool isConstSize = arraySize.IsConst();
  8092. BfIRBlock clearBlock;
  8093. BfIRBlock contBlock;
  8094. bool wantsDeinit = ((!IsOptimized()) && (!mIsComptimeModule) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly));
  8095. if (wantsDeinit)
  8096. {
  8097. BfIRBlock prevBlock;
  8098. if (!isConstSize)
  8099. {
  8100. clearBlock = mBfIRBuilder->CreateBlock("clear");
  8101. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  8102. prevBlock = mBfIRBuilder->GetInsertBlock();
  8103. mBfIRBuilder->AddBlock(clearBlock);
  8104. mBfIRBuilder->SetInsertPoint(clearBlock);
  8105. }
  8106. auto deferredCall = AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  8107. if (!isConstSize)
  8108. {
  8109. mBfIRBuilder->CreateBr(contBlock);
  8110. mBfIRBuilder->SetInsertPoint(prevBlock);
  8111. if (deferredCall != NULL)
  8112. {
  8113. // Zero out size args
  8114. for (int i = 1; i < deferredCall->mModuleMethodInstance.mMethodInstance->GetParamCount(); i++)
  8115. {
  8116. auto scopedArg = deferredCall->mScopeArgs[i];
  8117. if (scopedArg != deferredCall->mOrigScopeArgs[i])
  8118. mBfIRBuilder->CreateStore(GetDefaultValue(deferredCall->mModuleMethodInstance.mMethodInstance->GetParamType(i)), deferredCall->mScopeArgs[i]);
  8119. }
  8120. }
  8121. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  8122. mBfIRBuilder->AddBlock(contBlock);
  8123. mBfIRBuilder->SetInsertPoint(contBlock);
  8124. }
  8125. }
  8126. }
  8127. return result;
  8128. }
  8129. }
  8130. else
  8131. {
  8132. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8133. {
  8134. // Generate and check new size
  8135. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8136. auto firstElementField = &arrayType->mFieldInstances.back();
  8137. int arrayClassSize = firstElementField->mDataOffset;
  8138. sizeValue = GetConstValue(arrayClassSize);
  8139. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8140. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8141. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  8142. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  8143. if (!noDtorCall)
  8144. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8145. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8146. return typedVal.mValue;
  8147. }
  8148. else
  8149. {
  8150. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8151. auto firstElementField = &arrayType->mFieldInstances.back();
  8152. if (!type->IsValuelessType())
  8153. {
  8154. int arrayClassSize = firstElementField->mDataOffset;
  8155. sizeValue = GetConstValue(arrayClassSize);
  8156. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8157. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8158. }
  8159. else
  8160. sizeValue = GetConstValue(arrayType->mInstSize);
  8161. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8162. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8163. if (!isDynAlloc)
  8164. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8165. else
  8166. {
  8167. MarkDynStack(scopeData);
  8168. SaveStackState(scopeData);
  8169. }
  8170. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  8171. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8172. if (!isDynAlloc)
  8173. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8174. auto allocaBlock = mBfIRBuilder->GetInsertBlock();
  8175. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8176. BfTypedValue typedVal;
  8177. if (!isDynAlloc)
  8178. {
  8179. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8180. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8181. mBfIRBuilder->ClearDebugLocation_Last();
  8182. mBfIRBuilder->SetInsertPoint(prevBlock);
  8183. allocaBlock = mCurMethodState->mIRInitBlock;
  8184. }
  8185. else
  8186. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8187. if (!noDtorCall)
  8188. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true, allocaBlock);
  8189. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8190. return typedVal.mValue;
  8191. }
  8192. }
  8193. }
  8194. else if (appendSizeValue)
  8195. {
  8196. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  8197. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  8198. // use the "dynSize" version conservatively
  8199. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8200. {
  8201. // Generate and check new size
  8202. sizeValue = GetConstValue(typeInstance->mInstSize);
  8203. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8204. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  8205. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  8206. if (!noDtorCall)
  8207. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  8208. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8209. return typedVal.mValue;
  8210. }
  8211. else // stack alloc, unlooped, with append
  8212. {
  8213. sizeValue = GetConstValue(typeInstance->mInstSize);
  8214. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8215. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8216. bool wasDynAlloc = isDynAlloc;
  8217. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8218. if (!isDynAlloc)
  8219. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8220. else
  8221. {
  8222. MarkDynStack(scopeData);
  8223. SaveStackState(scopeData);
  8224. }
  8225. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  8226. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  8227. if (!isDynAlloc)
  8228. {
  8229. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8230. }
  8231. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8232. bool mayBeLarge = false;
  8233. if (sizeValue.IsConst())
  8234. {
  8235. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  8236. if (constantInt->mInt64 >= 4096)
  8237. mayBeLarge = true;
  8238. }
  8239. else
  8240. mayBeLarge = true;
  8241. if (((type->IsObject() && (!mayBeLarge))) ||
  8242. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8243. ((zeroMemory) && (!mayBeLarge)))
  8244. {
  8245. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8246. }
  8247. BfIRValue castedVal;
  8248. if (!isDynAlloc)
  8249. {
  8250. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8251. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8252. mBfIRBuilder->ClearDebugLocation(castedVal);
  8253. mBfIRBuilder->SetInsertPoint(prevBlock);
  8254. if (WantsLifetimes())
  8255. {
  8256. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8257. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8258. }
  8259. }
  8260. else
  8261. {
  8262. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8263. }
  8264. auto typedVal = BfTypedValue(castedVal, typeInstance);
  8265. if (!noDtorCall)
  8266. {
  8267. bool doCondAlloca = false;
  8268. if (!IsTargetingBeefBackend())
  8269. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  8270. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  8271. }
  8272. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8273. return typedVal.mValue;
  8274. }
  8275. }
  8276. else // "Normal" stack alloc
  8277. {
  8278. BF_ASSERT(!sizeValue);
  8279. //TODO: If sizeValue is a constant then do this in the head IR builder
  8280. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8281. if (!isLoopedAlloc)
  8282. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8283. else
  8284. {
  8285. MarkDynStack(scopeData);
  8286. SaveStackState(scopeData);
  8287. }
  8288. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  8289. if (!isLoopedAlloc)
  8290. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8291. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8292. bool mayBeLarge = allocSize >= 4096;
  8293. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  8294. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8295. ((zeroMemory) && (!mayBeLarge)))
  8296. {
  8297. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  8298. // and memset is always safe
  8299. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8300. }
  8301. auto typedVal = BfTypedValue(allocaInst, type);
  8302. if (!isLoopedAlloc)
  8303. {
  8304. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8305. mBfIRBuilder->SetInsertPoint(prevBlock);
  8306. if (WantsLifetimes())
  8307. {
  8308. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8309. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8310. }
  8311. }
  8312. if (!noDtorCall)
  8313. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8314. if (typeInstance != NULL)
  8315. {
  8316. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  8317. }
  8318. else
  8319. {
  8320. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  8321. }
  8322. return allocaInst;
  8323. }
  8324. }
  8325. else if (arraySize)
  8326. {
  8327. if (isRawArrayAlloc)
  8328. {
  8329. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8330. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  8331. }
  8332. else
  8333. {
  8334. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8335. typeInstance = arrayType;
  8336. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8337. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8338. appendSizeValue = elementDataSize;
  8339. if (!type->IsSizeAligned())
  8340. {
  8341. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  8342. }
  8343. }
  8344. }
  8345. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  8346. {
  8347. auto vDataRef = GetClassVDataPtr(typeInstance);
  8348. BfIRValue result;
  8349. bool isResultInitialized = false;
  8350. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8351. if (typeInstance->mTypeOptionsIdx != -1)
  8352. {
  8353. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8354. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8355. }
  8356. if (mIsComptimeModule)
  8357. stackCount = 0;
  8358. if (!sizeValue)
  8359. sizeValue = GetConstValue(typeInstance->mInstSize);
  8360. if (appendSizeValue)
  8361. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8362. BfIRValue origSizeValue = sizeValue;
  8363. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  8364. if (isAllocEx)
  8365. {
  8366. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  8367. if (prepareStackTraceMethod)
  8368. {
  8369. SizedArray<BfIRValue, 2> irArgs;
  8370. irArgs.Add(sizeValue);
  8371. irArgs.Add(GetConstValue(stackCount));
  8372. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  8373. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  8374. }
  8375. }
  8376. if (allocTarget.mCustomAllocator)
  8377. {
  8378. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8379. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  8380. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  8381. {
  8382. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8383. mBfIRBuilder->PopulateType(classVDataType);
  8384. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8385. mBfIRBuilder->PopulateType(typeInstType);
  8386. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  8387. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  8388. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  8389. BfTypedValueExpression typedValueExpr;
  8390. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  8391. typedValueExpr.mRefNode = allocTarget.mRefNode;
  8392. BfExprEvaluator exprEvaluator(this);
  8393. SizedArray<BfExpression*, 2> argExprs;
  8394. argExprs.push_back(&typedValueExpr);
  8395. BfTypedValueExpression sizeValueExpr;
  8396. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  8397. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  8398. argExprs.push_back(&sizeValueExpr);
  8399. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8400. BfResolvedArgs argValues(&sizedArgExprs);
  8401. exprEvaluator.ResolveArgValues(argValues);
  8402. exprEvaluator.mNoBind = true;
  8403. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, BfMethodGenericArguments());
  8404. if (allocResult)
  8405. {
  8406. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  8407. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  8408. else
  8409. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  8410. isResultInitialized = true;
  8411. }
  8412. }
  8413. }
  8414. bool wasAllocated = false;
  8415. if (!result)
  8416. {
  8417. if (hasCustomAllocator)
  8418. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  8419. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8420. {
  8421. SizedArray<BfIRValue, 4> llvmArgs;
  8422. llvmArgs.push_back(sizeValue);
  8423. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8424. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8425. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8426. wasAllocated = true;
  8427. }
  8428. }
  8429. if (result)
  8430. {
  8431. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8432. {
  8433. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  8434. SizedArray<BfIRValue, 4> llvmArgs;
  8435. llvmArgs.push_back(objectPtr);
  8436. llvmArgs.push_back(origSizeValue);
  8437. llvmArgs.push_back(vDataRef);
  8438. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  8439. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  8440. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  8441. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  8442. if (wasAllocated)
  8443. {
  8444. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  8445. auto bytePtrType = CreatePointerType(byteType);
  8446. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  8447. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  8448. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  8449. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  8450. }
  8451. }
  8452. else
  8453. {
  8454. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  8455. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8456. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  8457. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  8458. }
  8459. }
  8460. else
  8461. {
  8462. if ((mBfIRBuilder->mIgnoreWrites) ||
  8463. ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)))
  8464. return GetDefaultValue(typeInstance);
  8465. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8466. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  8467. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8468. {
  8469. SizedArray<BfIRValue, 4> llvmArgs;
  8470. llvmArgs.push_back(vData);
  8471. llvmArgs.push_back(sizeValue);
  8472. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  8473. llvmArgs.push_back(GetConstValue(stackCount));
  8474. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  8475. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  8476. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8477. }
  8478. else
  8479. {
  8480. SizedArray<BfIRValue, 4> llvmArgs;
  8481. llvmArgs.push_back(sizeValue);
  8482. BfIRFunction irFunc;
  8483. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8484. {
  8485. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  8486. irFunc = moduleMethodInstance.mFunc;
  8487. }
  8488. if (!irFunc)
  8489. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8490. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8491. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  8492. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  8493. if (mIsComptimeModule)
  8494. {
  8495. vdataPtr = mBfIRBuilder->CreateBitCast(vdataPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance())));
  8496. }
  8497. mBfIRBuilder->CreateStore(vData, vdataPtr);
  8498. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8499. }
  8500. }
  8501. if ((zeroMemory) && (arraySize))
  8502. {
  8503. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8504. typeInstance = arrayType;
  8505. auto firstElementField = &arrayType->mFieldInstances.back();
  8506. int arrayClassSize = firstElementField->mDataOffset;
  8507. BfIRValue elementDataSize;
  8508. bool skipZero = false;
  8509. if (arraySize.IsConst())
  8510. {
  8511. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8512. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8513. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  8514. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  8515. if (constVal->mInt64 <= 0)
  8516. skipZero = true;
  8517. }
  8518. else
  8519. {
  8520. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  8521. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8522. }
  8523. if (!skipZero)
  8524. {
  8525. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8526. auto ptrType = CreatePointerType(i8Type);
  8527. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  8528. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  8529. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  8530. appendSizeValue = elementDataSize;
  8531. }
  8532. }
  8533. return result;
  8534. }
  8535. else
  8536. {
  8537. if (!sizeValue)
  8538. sizeValue = GetConstValue(allocSize);
  8539. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  8540. }
  8541. }
  8542. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  8543. {
  8544. if ((type == NULL) || (refNode == NULL))
  8545. return;
  8546. auto typeInstance = type->ToTypeInstance();
  8547. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  8548. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  8549. }
  8550. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  8551. {
  8552. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8553. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8554. }
  8555. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  8556. {
  8557. if (sizeMultiple == 0)
  8558. sizeMultiple = align;
  8559. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  8560. {
  8561. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  8562. {
  8563. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8564. BF_ASSERT(localVar->mName == "appendIdx");
  8565. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  8566. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8567. if (align > 1)
  8568. {
  8569. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8570. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8571. }
  8572. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  8573. }
  8574. else
  8575. {
  8576. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  8577. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  8578. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  8579. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8580. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8581. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  8582. }
  8583. }
  8584. if (mCurMethodState->mCurAppendAlign == 0)
  8585. mCurMethodState->mCurAppendAlign = sizeMultiple;
  8586. else
  8587. {
  8588. if (sizeMultiple % align == 0)
  8589. mCurMethodState->mCurAppendAlign = align;
  8590. else
  8591. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  8592. }
  8593. }
  8594. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  8595. {
  8596. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8597. BF_ASSERT(localVar->mName == "appendIdx");
  8598. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  8599. BfIRValue retValue;
  8600. BfTypeInstance* retTypeInstance = NULL;
  8601. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  8602. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  8603. if (arraySize)
  8604. {
  8605. if (isRawArrayAlloc)
  8606. {
  8607. EmitAppendAlign(type->mAlign);
  8608. BfPointerType* ptrType = CreatePointerType(type);
  8609. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8610. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8611. if (mSystem->mPtrSize != 4)
  8612. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8613. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8614. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8615. if (zeroMemory)
  8616. {
  8617. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  8618. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  8619. }
  8620. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  8621. }
  8622. else
  8623. {
  8624. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8625. EmitAppendAlign(arrayType->mAlign, type->mSize);
  8626. auto firstElementField = &arrayType->mFieldInstances.back();
  8627. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  8628. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  8629. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8630. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8631. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8632. if (mSystem->mPtrSize != 4)
  8633. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8634. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8635. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8636. if (zeroMemory)
  8637. {
  8638. // Only zero out the actual elements
  8639. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  8640. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  8641. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  8642. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  8643. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  8644. }
  8645. retTypeInstance = arrayType;
  8646. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  8647. }
  8648. }
  8649. else
  8650. {
  8651. auto typeInst = type->ToTypeInstance();
  8652. BfIRValue sizeValue;
  8653. BfIRType toType;
  8654. if (typeInst != NULL)
  8655. {
  8656. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  8657. sizeValue = GetConstValue(typeInst->mInstSize);
  8658. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  8659. }
  8660. else
  8661. {
  8662. EmitAppendAlign(type->mAlign, type->mSize);
  8663. sizeValue = GetConstValue(type->mSize);
  8664. auto toPtrType = CreatePointerType(type);
  8665. toType = mBfIRBuilder->MapType(toPtrType);
  8666. }
  8667. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8668. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8669. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8670. retTypeInstance = typeInst;
  8671. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  8672. }
  8673. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  8674. {
  8675. mBfIRBuilder->PopulateType(retTypeInstance);
  8676. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  8677. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  8678. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  8679. auto curThis = GetThis();
  8680. BfIRValue newFlags;
  8681. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8682. {
  8683. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  8684. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  8685. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  8686. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  8687. }
  8688. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  8689. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  8690. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  8691. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8692. mBfIRBuilder->CreateStore(srcVal, destAddr);
  8693. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8694. {
  8695. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  8696. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  8697. }
  8698. }
  8699. if (appendSizeValue)
  8700. {
  8701. EmitAppendAlign(appendAllocAlign);
  8702. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8703. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  8704. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8705. }
  8706. return retValue;
  8707. }
  8708. bool BfModule::IsOptimized()
  8709. {
  8710. if (mProject == NULL)
  8711. return false;
  8712. if (mIsComptimeModule)
  8713. return false;
  8714. int optLevel = GetModuleOptions().mOptLevel;
  8715. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  8716. }
  8717. bool BfModule::IsTargetingBeefBackend()
  8718. {
  8719. if (mProject == NULL)
  8720. return true;
  8721. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  8722. }
  8723. bool BfModule::WantsLifetimes()
  8724. {
  8725. if (mBfIRBuilder->mIgnoreWrites)
  8726. return false;
  8727. if ((mIsComptimeModule) && (mBfIRBuilder->HasDebugLocation()))
  8728. return true;
  8729. else if (mProject == NULL)
  8730. return false;
  8731. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  8732. }
  8733. bool BfModule::HasCompiledOutput()
  8734. {
  8735. return (!mSystem->mIsResolveOnly) && (mGeneratesCode) && (!mIsComptimeModule);
  8736. }
  8737. bool BfModule::HasExecutedOutput()
  8738. {
  8739. return ((!mSystem->mIsResolveOnly) && (mGeneratesCode)) || (mIsComptimeModule);
  8740. }
  8741. // We will skip the object access check for any occurrences of this value
  8742. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  8743. {
  8744. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  8745. return;
  8746. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  8747. return;
  8748. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  8749. return;
  8750. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  8751. }
  8752. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  8753. {
  8754. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  8755. return;
  8756. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  8757. return;
  8758. if (typedVal.mValue.IsConst())
  8759. {
  8760. int stringIdx = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  8761. if (stringIdx != -1)
  8762. return;
  8763. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  8764. if (constant->mTypeCode == BfTypeCode_NullPtr)
  8765. return;
  8766. if (constant->mConstType == BfConstType_BitCastNull)
  8767. return;
  8768. }
  8769. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  8770. auto typeOptions = GetTypeOptions();
  8771. if (typeOptions != NULL)
  8772. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  8773. if (!emitObjectAccessCheck)
  8774. return;
  8775. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  8776. {
  8777. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  8778. return;
  8779. }
  8780. if (typedVal.IsAddr())
  8781. typedVal = LoadValue(typedVal);
  8782. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  8783. }
  8784. void BfModule::EmitEnsureInstructionAt()
  8785. {
  8786. if (mBfIRBuilder->mIgnoreWrites)
  8787. return;
  8788. if (mIsComptimeModule)
  8789. {
  8790. // Always add
  8791. }
  8792. else if ((mProject == NULL) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  8793. return;
  8794. mBfIRBuilder->CreateEnsureInstructionAt();
  8795. }
  8796. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  8797. {
  8798. if (mBfIRBuilder->mIgnoreWrites)
  8799. return; // Nothing needed here
  8800. auto irb = mBfIRBuilder;
  8801. auto checkBB = irb->CreateBlock("as.check");
  8802. auto isNull = irb->CreateIsNull(targetValue.mValue);
  8803. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  8804. if (mIsComptimeModule)
  8805. {
  8806. AddBasicBlock(checkBB);
  8807. auto callResult = mBfIRBuilder->Comptime_DynamicCastCheck(targetValue.mValue, targetType->mTypeId, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8808. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult, GetDefaultValue(mContext->mBfObjectType));
  8809. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8810. return;
  8811. }
  8812. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8813. auto intPtrType = CreatePointerType(intType);
  8814. auto intPtrPtrType = CreatePointerType(intPtrType);
  8815. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  8816. auto int32PtrType = CreatePointerType(int32Type);
  8817. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8818. if (mCompiler->mOptions.mAllowHotSwapping)
  8819. {
  8820. BfExprEvaluator exprEvaluator(this);
  8821. AddBasicBlock(checkBB);
  8822. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8823. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  8824. SizedArray<BfIRValue, 4> irArgs;
  8825. irArgs.push_back(objectParam);
  8826. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  8827. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  8828. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  8829. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8830. }
  8831. else
  8832. {
  8833. AddBasicBlock(checkBB);
  8834. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  8835. vDataPtr = irb->CreateLoad(vDataPtr);
  8836. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8837. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  8838. if (targetType->IsInterface())
  8839. {
  8840. auto targetTypeInst = targetType->ToTypeInstance();
  8841. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8842. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  8843. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  8844. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  8845. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  8846. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  8847. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  8848. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  8849. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  8850. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  8851. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  8852. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  8853. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8854. }
  8855. else
  8856. {
  8857. if (!targetType->IsTypeInstance())
  8858. targetType = GetWrappedStructType(targetType);
  8859. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8860. int inheritanceIdOfs = mSystem->mPtrSize;
  8861. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  8862. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  8863. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  8864. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  8865. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  8866. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  8867. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  8868. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  8869. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  8870. fieldInst = &typeTypeInstance->mFieldInstances[10];
  8871. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  8872. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  8873. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  8874. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  8875. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  8876. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8877. }
  8878. }
  8879. }
  8880. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  8881. {
  8882. if (mBfIRBuilder->mIgnoreWrites)
  8883. return;
  8884. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  8885. auto typeOptions = GetTypeOptions();
  8886. if (typeOptions != NULL)
  8887. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  8888. if (emitDynamicCastCheck)
  8889. {
  8890. int wantTypeId = 0;
  8891. if (!type->IsGenericParam())
  8892. wantTypeId = type->mTypeId;
  8893. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  8894. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  8895. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  8896. AddBasicBlock(failBlock);
  8897. if (mIsComptimeModule)
  8898. {
  8899. mBfIRBuilder->Comptime_Error(CeErrorKind_ObjectDynCheckFailed);
  8900. }
  8901. else
  8902. {
  8903. SizedArray<BfIRValue, 8> llvmArgs;
  8904. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8905. llvmArgs.push_back(bitAddr);
  8906. llvmArgs.push_back(GetConstValue32(wantTypeId));
  8907. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  8908. BF_ASSERT(objDynCheck);
  8909. if (objDynCheck)
  8910. {
  8911. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  8912. }
  8913. }
  8914. mBfIRBuilder->CreateBr(endBlock);
  8915. AddBasicBlock(endBlock);
  8916. }
  8917. }
  8918. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, BfCastFlags castFlags)
  8919. {
  8920. bool callDtor = (castFlags & BfCastFlags_NoBoxDtor) == 0;
  8921. bool wantConst = ((castFlags & BfCastFlags_WantsConst) != 0) && (typedVal.mValue.IsConst());
  8922. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  8923. {
  8924. if (toType == mContext->mBfObjectType)
  8925. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  8926. if (toType->IsBoxed())
  8927. {
  8928. BfBoxedType* boxedType = (BfBoxedType*)toType;
  8929. if (boxedType->mElementType->IsGenericParam())
  8930. {
  8931. if (typedVal.mType == boxedType->mElementType)
  8932. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  8933. else
  8934. return BfTypedValue();
  8935. }
  8936. }
  8937. }
  8938. BP_ZONE("BoxValue");
  8939. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  8940. if (typedVal.mType->IsNullable())
  8941. {
  8942. typedVal = MakeAddressable(typedVal);
  8943. auto innerType = typedVal.mType->GetUnderlyingType();
  8944. if (!innerType->IsValueType())
  8945. {
  8946. if (!mIgnoreErrors)
  8947. Fail("Only value types can be boxed", srcNode);
  8948. return BfTypedValue();
  8949. }
  8950. auto boxedType = CreateBoxedType(innerType);
  8951. auto resultType = toType;
  8952. if (resultType == NULL)
  8953. resultType = boxedType;
  8954. if (mBfIRBuilder->mIgnoreWrites)
  8955. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  8956. auto prevBB = mBfIRBuilder->GetInsertBlock();
  8957. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  8958. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  8959. mBfIRBuilder->PopulateType(typedVal.mType);
  8960. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  8961. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  8962. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  8963. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  8964. mBfIRBuilder->AddBlock(boxBB);
  8965. mBfIRBuilder->SetInsertPoint(boxBB);
  8966. BfScopeData newScope;
  8967. newScope.mOuterIsConditional = true;
  8968. mCurMethodState->AddScope(&newScope);
  8969. NewScopeState();
  8970. BfIRValue nullableValueAddr;
  8971. BfIRValue loadedVal;
  8972. if (innerType->IsValuelessType())
  8973. {
  8974. loadedVal = mBfIRBuilder->GetFakeVal();
  8975. }
  8976. else
  8977. {
  8978. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  8979. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  8980. }
  8981. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor ? BfCastFlags_None : BfCastFlags_NoBoxDtor);
  8982. RestoreScopeState();
  8983. if (!boxedVal)
  8984. return BfTypedValue();
  8985. mBfIRBuilder->CreateBr(endBB);
  8986. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  8987. mBfIRBuilder->AddBlock(endBB);
  8988. mBfIRBuilder->SetInsertPoint(endBB);
  8989. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  8990. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  8991. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  8992. return BfTypedValue(phi, resultType);
  8993. }
  8994. bool alreadyCheckedCast = false;
  8995. BfTypeInstance* toTypeInstance = NULL;
  8996. if (toType != NULL)
  8997. toTypeInstance = toType->ToTypeInstance();
  8998. bool isStructPtr = typedVal.mType->IsStructPtr();
  8999. if (fromStructTypeInstance == NULL)
  9000. {
  9001. auto primType = (BfPrimitiveType*)typedVal.mType;
  9002. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  9003. {
  9004. // Can always do IHashable
  9005. alreadyCheckedCast = true;
  9006. }
  9007. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  9008. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9009. else
  9010. {
  9011. auto checkStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9012. if (checkStructTypeInstance == toType->GetUnderlyingType())
  9013. fromStructTypeInstance = checkStructTypeInstance;
  9014. }
  9015. if (isStructPtr)
  9016. {
  9017. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9018. alreadyCheckedCast = true;
  9019. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  9020. }
  9021. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  9022. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9023. }
  9024. if (fromStructTypeInstance == NULL)
  9025. return BfTypedValue();
  9026. // Need to box it
  9027. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  9028. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9029. {
  9030. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9031. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  9032. auto boxedType = CreateBoxedType(typedVal.mType);
  9033. mBfIRBuilder->PopulateType(boxedType);
  9034. if (wantConst)
  9035. return BfTypedValue(mBfIRBuilder->CreateConstBox(typedVal.mValue, mBfIRBuilder->MapType(boxedType)), boxedType);
  9036. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9037. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  9038. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  9039. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  9040. if (boxedType->IsUnspecializedType())
  9041. {
  9042. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  9043. }
  9044. else
  9045. {
  9046. PopulateType(fromStructTypeInstance);
  9047. if (!fromStructTypeInstance->IsValuelessType())
  9048. {
  9049. typedVal = LoadValue(typedVal);
  9050. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  9051. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  9052. {
  9053. auto ptrType = CreatePointerType(typedVal.mType);
  9054. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  9055. }
  9056. if (typedVal.IsSplat())
  9057. {
  9058. AggregateSplatIntoAddr(typedVal, valPtr);
  9059. }
  9060. else
  9061. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  9062. }
  9063. }
  9064. if (toType == NULL)
  9065. {
  9066. return BfTypedValue(allocaInst, boxedType);
  9067. }
  9068. else
  9069. {
  9070. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  9071. return BfTypedValue(castedValue, toType);
  9072. }
  9073. }
  9074. return BfTypedValue();
  9075. }
  9076. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  9077. {
  9078. BfTypeInstance* checkTypeInst = typeInst;
  9079. while (checkTypeInst != NULL)
  9080. {
  9081. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  9082. {
  9083. if (checkProp->mName == propDef->mName)
  9084. {
  9085. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  9086. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  9087. {
  9088. propDef = checkProp;
  9089. typeInst = checkTypeInst;
  9090. return true;
  9091. }
  9092. }
  9093. }
  9094. checkTypeInst = checkTypeInst->mBaseType;
  9095. }
  9096. return false;
  9097. }
  9098. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  9099. {
  9100. if (!typeInstance->mResolvingVarField)
  9101. {
  9102. if (!typeInstance->DefineStateAllowsStaticMethods())
  9103. PopulateType(typeInstance, BfPopulateType_AllowStaticMethods);
  9104. }
  9105. else
  9106. {
  9107. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  9108. {
  9109. AssertErrorState();
  9110. return NULL;
  9111. }
  9112. }
  9113. if (assertName != NULL)
  9114. {
  9115. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9116. }
  9117. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9118. {
  9119. if (mCompiler->EnsureCeUnpaused(typeInstance))
  9120. {
  9121. BF_FATAL("OOB in GetRawMethodInstanceAtIdx");
  9122. }
  9123. return NULL;
  9124. }
  9125. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  9126. if (methodGroup.mDefault == NULL)
  9127. {
  9128. if (!mCompiler->mIsResolveOnly)
  9129. {
  9130. // Get it from the owning module so we don't create a reference prematurely...
  9131. auto declModule = typeInstance->mModule;
  9132. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  9133. {
  9134. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9135. if (!declModule->mIsScratchModule)
  9136. declModule->mOnDemandMethodCount++;
  9137. }
  9138. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  9139. (typeInstance->mTypeFailed) || (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted));
  9140. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  9141. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9142. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified);
  9143. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9144. }
  9145. else
  9146. {
  9147. auto declModule = typeInstance->mModule;
  9148. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass);
  9149. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9150. }
  9151. }
  9152. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9153. //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
  9154. // be from a call to the NON-raw version
  9155. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  9156. // {
  9157. // methodInstance->mIsReified = mIsReified;
  9158. // if (methodInstance->mMethodProcessRequest == NULL)
  9159. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  9160. // }
  9161. return methodInstance;
  9162. }
  9163. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  9164. {
  9165. if (methodDef->mIsLocalMethod)
  9166. {
  9167. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  9168. }
  9169. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx, NULL);
  9170. }
  9171. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  9172. {
  9173. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9174. while (typeInstance != NULL)
  9175. {
  9176. typeInstance->mTypeDef->PopulateMemberSets();
  9177. BfMemberSetEntry* entry = NULL;
  9178. BfMethodDef* methodDef = NULL;
  9179. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9180. methodDef = (BfMethodDef*)entry->mMemberDef;
  9181. while (methodDef != NULL)
  9182. {
  9183. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  9184. (methodDef->mGenericParams.size() == 0) &&
  9185. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9186. return GetRawMethodInstance(typeInstance, methodDef);
  9187. methodDef = methodDef->mNextWithSameName;
  9188. }
  9189. if (!checkBase)
  9190. break;
  9191. typeInstance = typeInstance->mBaseType;
  9192. }
  9193. return NULL;
  9194. }
  9195. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  9196. {
  9197. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9198. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  9199. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  9200. if (!useUnspecializedType)
  9201. return methodInstance;
  9202. if (!owner->IsGenericTypeInstance())
  9203. return methodInstance;
  9204. if ((owner->IsDelegateFromTypeRef()) ||
  9205. (owner->IsFunctionFromTypeRef()) ||
  9206. (owner->IsTuple()))
  9207. {
  9208. return methodInstance;
  9209. }
  9210. auto genericType = (BfTypeInstance*)owner;
  9211. if ((genericType->IsUnspecializedType()) && (!genericType->IsUnspecializedTypeVariation()))
  9212. return methodInstance;
  9213. if (methodInstance->mMethodDef->mIsLocalMethod)
  9214. return methodInstance;
  9215. if (methodInstance->mMethodDef->mDeclaringType->IsEmitted())
  9216. return methodInstance;
  9217. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef->GetDefinition());
  9218. if (unspecializedType == NULL)
  9219. {
  9220. AssertErrorState();
  9221. return methodInstance;
  9222. }
  9223. if (unspecializedType == NULL)
  9224. return methodInstance;
  9225. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  9226. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  9227. }
  9228. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  9229. {
  9230. int genericCount = 0;
  9231. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  9232. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  9233. {
  9234. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  9235. if (param->IsGenericParam())
  9236. genericCount++;
  9237. }
  9238. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  9239. genericCount++;
  9240. return genericCount;
  9241. }
  9242. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  9243. {
  9244. BF_ASSERT(!mIsScratchModule);
  9245. BF_ASSERT(mIsReified);
  9246. BfModule* mainModule = this;
  9247. if (mParentModule != NULL)
  9248. mainModule = mParentModule;
  9249. BfModule* specModule = NULL;
  9250. BfModule** specModulePtr = NULL;
  9251. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  9252. {
  9253. return *specModulePtr;
  9254. }
  9255. else
  9256. {
  9257. String specModuleName = mModuleName;
  9258. for (auto bfProject : projectList)
  9259. {
  9260. specModuleName += StrFormat("@%s", bfProject->mSafeName.c_str());
  9261. }
  9262. specModule = new BfModule(mContext, specModuleName);
  9263. specModule->mProject = mainModule->mProject;
  9264. specModule->mParentModule = mainModule;
  9265. specModule->mIsSpecializedMethodModuleRoot = true;
  9266. specModule->Init();
  9267. Array<BfProject*> projList;
  9268. for (auto project : projectList)
  9269. projList.Add(project);
  9270. mainModule->mSpecializedMethodModules[projList] = specModule;
  9271. }
  9272. return specModule;
  9273. }
  9274. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  9275. {
  9276. if (IsSkippingExtraResolveChecks())
  9277. return BfIRValue();
  9278. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  9279. {
  9280. //BF_ASSERT(!methodInstance->mIRFunction);
  9281. return BfIRValue();
  9282. }
  9283. auto methodDef = methodInstance->mMethodDef;
  9284. StringT<128> methodName;
  9285. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  9286. if (isInlined != methodInstance->mAlwaysInline)
  9287. {
  9288. if (isInlined)
  9289. methodName += "__INLINE";
  9290. else
  9291. methodName += "__NOINLINE";
  9292. }
  9293. if (tryExisting)
  9294. {
  9295. auto func = mBfIRBuilder->GetFunction(methodName);
  9296. if (func)
  9297. return func;
  9298. }
  9299. auto intrinsic = GetIntrinsic(methodInstance);
  9300. if (intrinsic)
  9301. return intrinsic;
  9302. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  9303. {
  9304. return CreateDllImportGlobalVar(methodInstance, false);
  9305. }
  9306. BfIRType returnType;
  9307. SizedArray<BfIRType, 8> paramTypes;
  9308. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  9309. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  9310. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  9311. auto callingConv = GetIRCallingConvention(methodInstance);
  9312. if (callingConv != BfIRCallingConv_CDecl)
  9313. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  9314. SetupIRMethod(methodInstance, func, isInlined);
  9315. // auto srcModule = methodInstance->GetOwner()->GetModule();
  9316. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  9317. // {
  9318. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  9319. // {
  9320. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  9321. // }
  9322. // }
  9323. return func;
  9324. }
  9325. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  9326. {
  9327. if (assertName != NULL)
  9328. {
  9329. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9330. }
  9331. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9332. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9333. BfMethodDef* methodDef = NULL;
  9334. BfTypeInstance* foreignType = NULL;
  9335. if (methodInstance != NULL)
  9336. {
  9337. methodDef = methodInstance->mMethodDef;
  9338. if (methodInstance->mMethodInfoEx != NULL)
  9339. foreignType = methodInstance->mMethodInfoEx->mForeignType;
  9340. }
  9341. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  9342. {
  9343. // Can't use it, not reified
  9344. methodInstance = NULL;
  9345. }
  9346. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  9347. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  9348. {
  9349. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  9350. return BfModuleMethodInstance(methodInstance, func);
  9351. }
  9352. if (foreignType != NULL)
  9353. return GetMethodInstance(typeInstance, methodDef, BfTypeVector(), (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef), foreignType);
  9354. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  9355. }
  9356. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9357. {
  9358. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9359. while (typeInstance != NULL)
  9360. {
  9361. typeInstance->mTypeDef->PopulateMemberSets();
  9362. BfMemberSetEntry* entry = NULL;
  9363. BfMethodDef* methodDef = NULL;
  9364. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9365. methodDef = (BfMethodDef*)entry->mMemberDef;
  9366. while (methodDef != NULL)
  9367. {
  9368. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9369. (methodDef->mGenericParams.size() == 0) &&
  9370. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9371. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9372. methodDef = methodDef->mNextWithSameName;
  9373. }
  9374. if (!checkBase)
  9375. break;
  9376. typeInstance = typeInstance->mBaseType;
  9377. }
  9378. return BfModuleMethodInstance();
  9379. }
  9380. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  9381. {
  9382. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9383. while (typeInstance != NULL)
  9384. {
  9385. typeInstance->mTypeDef->PopulateMemberSets();
  9386. BfMemberSetEntry* entry = NULL;
  9387. BfMethodDef* methodDef = NULL;
  9388. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9389. methodDef = (BfMethodDef*)entry->mMemberDef;
  9390. while (methodDef != NULL)
  9391. {
  9392. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9393. (methodDef->mGenericParams.size() == 0) &&
  9394. (paramTypes.size() == methodDef->mParams.size()))
  9395. {
  9396. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9397. if (moduleMethodInstance.mMethodInstance != NULL)
  9398. {
  9399. bool matches = true;
  9400. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  9401. {
  9402. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  9403. matches = false;
  9404. }
  9405. if (matches)
  9406. return moduleMethodInstance;
  9407. }
  9408. }
  9409. methodDef = methodDef->mNextWithSameName;
  9410. }
  9411. if (!checkBase)
  9412. break;
  9413. typeInstance = typeInstance->mBaseType;
  9414. }
  9415. return BfModuleMethodInstance();
  9416. }
  9417. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  9418. {
  9419. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  9420. PopulateType(internalType);
  9421. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  9422. if (!moduleMethodInstance)
  9423. {
  9424. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  9425. }
  9426. return moduleMethodInstance;
  9427. }
  9428. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  9429. {
  9430. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  9431. typeInstance->mOperatorInfo.Add(NULL);
  9432. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  9433. {
  9434. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  9435. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  9436. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  9437. BfTypeState typeState;
  9438. typeState.mType = typeInstance;
  9439. typeState.mCurTypeDef = operatorDef->mDeclaringType;
  9440. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  9441. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  9442. if (operatorDef->mReturnTypeRef != NULL)
  9443. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  9444. if (operatorDef->mParams.size() >= 1)
  9445. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  9446. if (operatorDef->mParams.size() >= 2)
  9447. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  9448. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  9449. }
  9450. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  9451. }
  9452. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  9453. {
  9454. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  9455. if (operatorInfo == NULL)
  9456. return NULL;
  9457. if (operatorInfo->mReturnType == NULL)
  9458. return NULL;
  9459. auto castFlags = BfCastFlags_IsConstraintCheck;
  9460. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9461. castFlags = (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator);
  9462. if (lhs)
  9463. {
  9464. if (operatorInfo->mLHSType == NULL)
  9465. return NULL;
  9466. if (!CanCast(lhs, operatorInfo->mLHSType, castFlags))
  9467. return NULL;
  9468. }
  9469. if (rhs)
  9470. {
  9471. if (operatorInfo->mRHSType == NULL)
  9472. return NULL;
  9473. if (!CanCast(rhs, operatorInfo->mRHSType, castFlags))
  9474. return NULL;
  9475. }
  9476. return operatorInfo->mReturnType;
  9477. }
  9478. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9479. {
  9480. while (typeInstance != NULL)
  9481. {
  9482. typeInstance->mTypeDef->PopulateMemberSets();
  9483. BfMemberSetEntry* entry = NULL;
  9484. BfMethodDef* methodDef = NULL;
  9485. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9486. methodDef = (BfMethodDef*)entry->mMemberDef;
  9487. while (methodDef != NULL)
  9488. {
  9489. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9490. (methodDef->mGenericParams.size() == 0) &&
  9491. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9492. {
  9493. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  9494. if (!methodInstanceGroup.IsImplemented())
  9495. return false;
  9496. if (methodInstanceGroup.mDefault == NULL)
  9497. return false;
  9498. return methodInstanceGroup.mDefault->mIsReified;
  9499. }
  9500. methodDef = methodDef->mNextWithSameName;
  9501. }
  9502. if (!checkBase)
  9503. break;
  9504. typeInstance = typeInstance->mBaseType;
  9505. }
  9506. return false;
  9507. }
  9508. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9509. {
  9510. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9511. while (typeInstance != NULL)
  9512. {
  9513. typeInstance->mTypeDef->PopulateMemberSets();
  9514. BfMemberSetEntry* entry = NULL;
  9515. BfMethodDef* methodDef = NULL;
  9516. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9517. methodDef = (BfMethodDef*)entry->mMemberDef;
  9518. while (methodDef != NULL)
  9519. {
  9520. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  9521. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9522. return true;
  9523. methodDef = methodDef->mNextWithSameName;
  9524. }
  9525. if (!checkBase)
  9526. break;
  9527. typeInstance = typeInstance->mBaseType;
  9528. }
  9529. return BfModuleMethodInstance();
  9530. }
  9531. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* typeGenericArgs, BfTypeVector* methodGenericArgs)
  9532. {
  9533. auto methodDef = methodInst->mMethodDef;
  9534. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  9535. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9536. bool hasGenericArgs = (typeGenericArgs != NULL) || (methodGenericArgs != NULL);
  9537. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  9538. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9539. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs);
  9540. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  9541. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9542. if (allowResolveGenericParamNames)
  9543. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9544. StringT<128> methodName;
  9545. auto _AddTypeName = [&](BfType* type)
  9546. {
  9547. auto typeNameFlags = BfTypeNameFlags_None;
  9548. if (allowResolveGenericParamNames)
  9549. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9550. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9551. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs);
  9552. methodName += TypeToString(type, typeNameFlags);
  9553. };
  9554. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  9555. {
  9556. _AddTypeName(methodInst->mReturnType);
  9557. methodName += " ";
  9558. }
  9559. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  9560. {
  9561. methodName += TypeToString(type, typeNameFlags);
  9562. if (methodName == "$")
  9563. methodName = "";
  9564. else if (!methodName.IsEmpty())
  9565. methodName += ".";
  9566. }
  9567. String accessorString;
  9568. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  9569. if (methodInst->mMethodDef->mIsLocalMethod)
  9570. {
  9571. int atPos = (int)methodDefName.IndexOf('$');
  9572. methodDefName.RemoveToEnd(atPos);
  9573. methodDefName.Replace("@", ".");
  9574. }
  9575. else
  9576. {
  9577. int atPos = (int)methodDefName.IndexOf('$');
  9578. if (atPos != -1)
  9579. {
  9580. accessorString = methodDefName.Substring(0, atPos);
  9581. if ((accessorString == "get") || (accessorString == "set"))
  9582. {
  9583. methodDefName = methodDefName.Substring(atPos + 1);
  9584. }
  9585. else
  9586. accessorString = "";
  9587. }
  9588. }
  9589. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  9590. {
  9591. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9592. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9593. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9594. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  9595. methodName += ".";
  9596. }
  9597. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  9598. {
  9599. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9600. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9601. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9602. methodName += "[";
  9603. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  9604. methodName += "].";
  9605. }
  9606. if (methodDef->mMethodType == BfMethodType_Operator)
  9607. {
  9608. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  9609. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9610. {
  9611. // Don't add explicit/implicit part, since that's not available in GCC mangling
  9612. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  9613. {
  9614. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  9615. methodName += "explicit ";
  9616. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  9617. methodName += "explicit ";
  9618. }*/
  9619. methodName += "operator ";
  9620. if (methodInst->mReturnType != NULL)
  9621. methodName += TypeToString(methodInst->mReturnType);
  9622. }
  9623. else
  9624. {
  9625. methodName += "operator";
  9626. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  9627. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  9628. }
  9629. }
  9630. else if (methodDef->mMethodType == BfMethodType_Ctor)
  9631. {
  9632. if (methodDef->mIsStatic)
  9633. methodName += "__BfStaticCtor";
  9634. else
  9635. methodName += "this";
  9636. accessorString = "";
  9637. }
  9638. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  9639. {
  9640. auto propertyDecl = methodDef->GetPropertyDeclaration();
  9641. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  9642. {
  9643. methodName += "get indexer";
  9644. }
  9645. else
  9646. {
  9647. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  9648. propertyDecl->mNameNode->ToString(methodName);
  9649. methodName += " get accessor";
  9650. return methodName;
  9651. }
  9652. }
  9653. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  9654. {
  9655. auto propertyDecl = methodDef->GetPropertyDeclaration();
  9656. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  9657. {
  9658. methodName += "set indexer";
  9659. }
  9660. else
  9661. {
  9662. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  9663. propertyDecl->mNameNode->ToString(methodName);
  9664. methodName += " set accessor";
  9665. return methodName;
  9666. }
  9667. }
  9668. else
  9669. methodName += methodDefName;
  9670. if (methodDef->mMethodType == BfMethodType_Mixin)
  9671. methodName += "!";
  9672. BfTypeVector newMethodGenericArgs;
  9673. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9674. {
  9675. methodName += "<";
  9676. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  9677. {
  9678. if (i > 0)
  9679. methodName += ", ";
  9680. BfTypeNameFlags typeNameFlags = BfTypeNameFlag_ShortConst;
  9681. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  9682. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9683. if (allowResolveGenericParamNames)
  9684. typeNameFlags = (BfTypeNameFlags)(typeNameFlags | BfTypeNameFlag_ResolveGenericParamNames);
  9685. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  9686. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  9687. {
  9688. bool hasEmpty = false;
  9689. for (auto arg : *methodGenericArgs)
  9690. {
  9691. if (arg == NULL)
  9692. hasEmpty = true;
  9693. }
  9694. if (hasEmpty)
  9695. {
  9696. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  9697. {
  9698. auto arg = (*methodGenericArgs)[genericIdx];
  9699. if (arg != NULL)
  9700. newMethodGenericArgs.push_back(arg);
  9701. else
  9702. {
  9703. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  9704. if (genericParamInst->mTypeConstraint != NULL)
  9705. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  9706. else
  9707. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  9708. }
  9709. }
  9710. methodGenericArgs = &newMethodGenericArgs;
  9711. }
  9712. if (type->IsUnspecializedType())
  9713. type = ResolveGenericType(type, NULL, methodGenericArgs);
  9714. }
  9715. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  9716. {
  9717. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  9718. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  9719. methodName += TypeToString(type, typeNameFlags);
  9720. }
  9721. else
  9722. methodName += TypeToString(type, typeNameFlags);
  9723. }
  9724. methodName += ">";
  9725. }
  9726. if (accessorString.length() == 0)
  9727. {
  9728. int dispParamIdx = 0;
  9729. methodName += "(";
  9730. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  9731. {
  9732. int paramKind = methodInst->GetParamKind(paramIdx);
  9733. if (paramKind == BfParamKind_ImplicitCapture)
  9734. continue;
  9735. if (dispParamIdx > 0)
  9736. methodName += ", ";
  9737. if (paramKind == BfParamKind_Params)
  9738. methodName += "params ";
  9739. BfType* type = methodInst->GetParamType(paramIdx);
  9740. _AddTypeName(type);
  9741. methodName += " ";
  9742. methodName += methodInst->GetParamName(paramIdx);
  9743. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  9744. if ((paramInitializer != NULL) && ((methodNameFlags & BfMethodNameFlag_NoAst) == 0))
  9745. {
  9746. methodName += " = ";
  9747. methodName += paramInitializer->ToString();
  9748. }
  9749. dispParamIdx++;
  9750. }
  9751. methodName += ")";
  9752. }
  9753. if (accessorString.length() != 0)
  9754. {
  9755. methodName += " ";
  9756. methodName += accessorString;
  9757. }
  9758. if ((methodNameFlags & BfMethodNameFlag_IncludeMut) != 0)
  9759. {
  9760. if ((methodDef->mIsMutating) && (methodInst->GetOwner()->IsValueType()))
  9761. methodName += " mut";
  9762. }
  9763. return methodName;
  9764. }
  9765. void BfModule::pt(BfType* type)
  9766. {
  9767. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  9768. }
  9769. void BfModule::pm(BfMethodInstance* type)
  9770. {
  9771. OutputDebugStrF("%s\n", MethodToString(type).c_str());
  9772. }
  9773. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  9774. {
  9775. if ((flagsLeft & checkFlag) == 0)
  9776. return;
  9777. if (!str.empty())
  9778. {
  9779. if (flagsLeft == checkFlag)
  9780. {
  9781. if ((int)str.IndexOf(',') != -1)
  9782. str += ", and ";
  9783. else
  9784. str += " and ";
  9785. }
  9786. else
  9787. str += ", ";
  9788. }
  9789. str += addString;
  9790. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  9791. }
  9792. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  9793. {
  9794. String resultStr;
  9795. auto flagsLeft = attrTarget;
  9796. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  9797. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  9798. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  9799. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  9800. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  9801. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  9802. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  9803. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  9804. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  9805. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  9806. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  9807. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  9808. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  9809. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  9810. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  9811. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  9812. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  9813. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  9814. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  9815. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  9816. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  9817. if (resultStr.IsEmpty())
  9818. return "<nothing>";
  9819. return resultStr;
  9820. }
  9821. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  9822. {
  9823. auto constant = mBfIRBuilder->GetConstant(irVal);
  9824. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  9825. if (stringPoolIdx != -1)
  9826. {
  9827. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  9828. return;
  9829. }
  9830. if (constant->mConstType == BfConstType_Agg)
  9831. {
  9832. auto constArray = (BfConstantAgg*)constant;
  9833. SizedArray<BfIRValue, 8> newVals;
  9834. for (auto val : constArray->mValues)
  9835. {
  9836. auto newVal = val;
  9837. CurrentAddToConstHolder(newVal);
  9838. newVals.push_back(newVal);
  9839. }
  9840. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstAgg(constArray->mType, newVals);
  9841. return;
  9842. }
  9843. auto origConst = irVal;
  9844. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  9845. {
  9846. auto bitcast = (BfConstantBitCast*)constant;
  9847. BfIRValue newVal;
  9848. if (bitcast->mTarget)
  9849. {
  9850. newVal = BfIRValue(BfIRValueFlags_Const, bitcast->mTarget);
  9851. CurrentAddToConstHolder(newVal);
  9852. }
  9853. else
  9854. newVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstNull();
  9855. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstBitCast(newVal, bitcast->mToType);
  9856. return;
  9857. }
  9858. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  9859. }
  9860. void BfModule::ClearConstData()
  9861. {
  9862. mBfIRBuilder->ClearConstData();
  9863. mStringObjectPool.Clear();
  9864. mStringCharPtrPool.Clear();
  9865. mStringPoolRefs.Clear();
  9866. mUnreifiedStringPoolRefs.Clear();
  9867. }
  9868. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  9869. {
  9870. switch (constant->mTypeCode)
  9871. {
  9872. case BfTypeCode_StringId:
  9873. case BfTypeCode_Boolean:
  9874. case BfTypeCode_Int8:
  9875. case BfTypeCode_UInt8:
  9876. case BfTypeCode_Int16:
  9877. case BfTypeCode_UInt16:
  9878. case BfTypeCode_Int32:
  9879. case BfTypeCode_UInt32:
  9880. case BfTypeCode_Int64:
  9881. case BfTypeCode_UInt64:
  9882. case BfTypeCode_IntPtr:
  9883. case BfTypeCode_UIntPtr:
  9884. case BfTypeCode_IntUnknown:
  9885. case BfTypeCode_UIntUnknown:
  9886. case BfTypeCode_Char8:
  9887. case BfTypeCode_Char16:
  9888. case BfTypeCode_Char32:
  9889. case BfTypeCode_Float:
  9890. case BfTypeCode_Double:
  9891. {
  9892. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  9893. BfTypedValue typedValue;
  9894. bool allowUnactualized = mBfIRBuilder->mIgnoreWrites;
  9895. if (constant->mTypeCode == BfTypeCode_StringId)
  9896. {
  9897. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  9898. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  9899. {
  9900. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType, allowUnactualized), wantType);
  9901. return typedValue;
  9902. }
  9903. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  9904. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType, allowUnactualized), stringType);
  9905. }
  9906. if (!typedValue)
  9907. {
  9908. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  9909. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  9910. }
  9911. if (typedValue.mType == wantType)
  9912. return typedValue;
  9913. if (wantType->IsTypedPrimitive())
  9914. {
  9915. if (typedValue.mType == wantType->GetUnderlyingType())
  9916. {
  9917. typedValue.mType = wantType;
  9918. return typedValue;
  9919. }
  9920. }
  9921. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  9922. if (!castedTypedValue)
  9923. return BfTypedValue();
  9924. return castedTypedValue;
  9925. }
  9926. break;
  9927. default: break;
  9928. }
  9929. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  9930. BF_ASSERT(irValue);
  9931. if (!irValue)
  9932. return BfTypedValue();
  9933. if (constant->mConstType == BfConstType_GlobalVar)
  9934. {
  9935. mBfIRBuilder->PopulateType(wantType);
  9936. auto result = BfTypedValue(irValue, wantType, true);
  9937. if (!wantType->IsComposite())
  9938. result = LoadValue(result);
  9939. return result;
  9940. }
  9941. return BfTypedValue(irValue, wantType, false);
  9942. }
  9943. bool BfModule::HasUnactializedConstant(BfConstant* constant, BfIRConstHolder* constHolder)
  9944. {
  9945. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  9946. return true;
  9947. if (constant->mTypeCode == BfTypeCode_StringId)
  9948. return true;
  9949. if (constant->mConstType == BfConstType_Agg)
  9950. {
  9951. auto constArray = (BfConstantAgg*)constant;
  9952. for (auto val : constArray->mValues)
  9953. {
  9954. if (HasUnactializedConstant(constHolder->GetConstant(val), constHolder))
  9955. return true;
  9956. }
  9957. }
  9958. return false;
  9959. }
  9960. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType, bool allowUnactualized)
  9961. {
  9962. if (constant->mTypeCode == BfTypeCode_NullPtr)
  9963. {
  9964. if ((wantType == NULL) && (constant->mIRType.mKind == BfIRTypeData::TypeKind_TypeId))
  9965. wantType = mContext->mTypes[constant->mIRType.mId];
  9966. if (wantType == NULL)
  9967. return mBfIRBuilder->CreateConstNull();
  9968. return GetDefaultValue(wantType);
  9969. }
  9970. if (constant->mTypeCode == BfTypeCode_StringId)
  9971. {
  9972. if (!allowUnactualized)
  9973. {
  9974. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  9975. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  9976. {
  9977. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  9978. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  9979. if (wantType->IsPointer())
  9980. return GetStringCharPtr(stringObjConst, true);
  9981. return stringObjConst;
  9982. }
  9983. }
  9984. }
  9985. if (constant->mConstType == Beefy::BfConstType_TypeOf)
  9986. {
  9987. auto constTypeOf = (BfTypeOf_Const*)constant;
  9988. if (mCurTypeInstance != NULL)
  9989. AddDependency(constTypeOf->mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9990. return CreateTypeDataRef(constTypeOf->mType);
  9991. }
  9992. if (constant->mConstType == BfConstType_PtrToInt)
  9993. {
  9994. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  9995. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  9996. return mBfIRBuilder->CreatePtrToInt(ConstantToCurrent(fromTarget, constHolder, NULL), fromPtrToInt->mToTypeCode);
  9997. }
  9998. if (constant->mConstType == BfConstType_IntToPtr)
  9999. {
  10000. auto fromPtrToInt = (BfConstantIntToPtr*)constant;
  10001. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10002. BfIRType toIRType = fromPtrToInt->mToType;
  10003. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10004. {
  10005. auto toType = mContext->mTypes[toIRType.mId];
  10006. toIRType = mBfIRBuilder->MapType(toType);
  10007. }
  10008. return mBfIRBuilder->CreateIntToPtr(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10009. }
  10010. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10011. {
  10012. auto bitcast = (BfConstantBitCast*)constant;
  10013. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  10014. BfIRType toIRType = bitcast->mToType;
  10015. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10016. {
  10017. auto toType = mContext->mTypes[toIRType.mId];
  10018. toIRType = mBfIRBuilder->MapType(toType);
  10019. }
  10020. return mBfIRBuilder->CreateBitCast(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10021. }
  10022. if (constant->mConstType == BfConstType_Agg)
  10023. {
  10024. auto constArray = (BfConstantAgg*)constant;
  10025. if ((wantType == NULL) && (constArray->mType.mKind == BfIRTypeData::TypeKind_TypeId))
  10026. wantType = mContext->mTypes[constArray->mType.mId];
  10027. SizedArray<BfIRValue, 8> newVals;
  10028. if (wantType->IsSizedArray())
  10029. {
  10030. auto elementType = wantType->GetUnderlyingType();
  10031. for (auto val : constArray->mValues)
  10032. {
  10033. newVals.Add(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  10034. }
  10035. }
  10036. else
  10037. {
  10038. auto wantTypeInst = wantType->ToTypeInstance();
  10039. if (wantTypeInst->mBaseType != NULL)
  10040. {
  10041. auto baseVal = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[0]), constHolder, wantTypeInst->mBaseType);
  10042. newVals.Add(baseVal);
  10043. }
  10044. if (wantType->IsUnion())
  10045. {
  10046. auto innerType = wantType->ToTypeInstance()->GetUnionInnerType();
  10047. if (!innerType->IsValuelessType())
  10048. {
  10049. auto val = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[1]), constHolder, innerType);
  10050. newVals.Add(val);
  10051. }
  10052. }
  10053. if ((!wantType->IsUnion()) || (wantType->IsPayloadEnum()))
  10054. {
  10055. for (auto& fieldInstance : wantTypeInst->mFieldInstances)
  10056. {
  10057. if (fieldInstance.mDataIdx < 0)
  10058. continue;
  10059. auto val = constArray->mValues[fieldInstance.mDataIdx];
  10060. BfIRValue memberVal = ConstantToCurrent(constHolder->GetConstant(val), constHolder, fieldInstance.mResolvedType);
  10061. if (fieldInstance.mDataIdx == newVals.mSize)
  10062. newVals.Add(memberVal);
  10063. else
  10064. {
  10065. while (fieldInstance.mDataIdx >= newVals.mSize)
  10066. newVals.Add(BfIRValue());
  10067. newVals[fieldInstance.mDataIdx] = memberVal;
  10068. }
  10069. }
  10070. }
  10071. for (auto& val : newVals)
  10072. {
  10073. if (!val)
  10074. val = mBfIRBuilder->CreateConstArrayZero(0);
  10075. }
  10076. }
  10077. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(wantType, BfIRPopulateType_Identity), newVals);
  10078. }
  10079. return mBfIRBuilder->CreateConst(constant, constHolder);
  10080. }
  10081. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  10082. {
  10083. if (attrTarget == BfAttributeTargets_SkipValidate)
  10084. return;
  10085. for (auto& customAttribute : customAttributes->mAttributes)
  10086. {
  10087. if (!customAttribute.mAwaitingValidation)
  10088. continue;
  10089. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  10090. {
  10091. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  10092. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  10093. }
  10094. customAttribute.mAwaitingValidation = false;
  10095. }
  10096. }
  10097. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10098. {
  10099. bool allowNonConstArgs = (flags & BfGetCustomAttributesFlags_AllowNonConstArgs) != 0;
  10100. bool keepConstsInModule = (flags & BfGetCustomAttributesFlags_KeepConstsInModule) != 0;
  10101. if (!mCompiler->mHasRequiredTypes)
  10102. return;
  10103. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  10104. {
  10105. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  10106. sourceClassifier->VisitChild(attributesDirective);
  10107. }
  10108. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  10109. if (mCompiler->IsAutocomplete())
  10110. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  10111. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  10112. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  10113. BfTypeDef* activeTypeDef = GetActiveTypeDef();
  10114. BfAutoComplete* autoComplete = NULL;
  10115. if (mCompiler->mResolvePassData != NULL)
  10116. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  10117. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  10118. {
  10119. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  10120. {
  10121. if (captureInfo == NULL)
  10122. {
  10123. Fail("Capture specifiers can only be used in lambda allocations", tokenNode);
  10124. continue;
  10125. }
  10126. BfCaptureInfo::Entry captureEntry;
  10127. captureEntry.mCaptureType = (tokenNode->mToken == BfToken_Ampersand) ? BfCaptureType_Reference : BfCaptureType_Copy;
  10128. if (!attributesDirective->mArguments.IsEmpty())
  10129. {
  10130. captureEntry.mNameNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]);
  10131. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  10132. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  10133. }
  10134. captureInfo->mCaptures.Add(captureEntry);
  10135. continue;
  10136. }
  10137. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  10138. BfCustomAttribute customAttribute;
  10139. customAttribute.mAwaitingValidation = true;
  10140. customAttribute.mDeclaringType = activeTypeDef;
  10141. customAttribute.mRef = attributesDirective;
  10142. if (attributesDirective->mAttrOpenToken != NULL)
  10143. targetOverride = (BfAttributeTargets)0;
  10144. if (attributesDirective->mAttributeTypeRef == NULL)
  10145. {
  10146. AssertErrorState();
  10147. continue;
  10148. }
  10149. BfType* attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10150. BfTypeDef* attrTypeDef = NULL;
  10151. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  10152. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  10153. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10154. {
  10155. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  10156. if (attrTypeDef != NULL)
  10157. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  10158. }
  10159. bool isBypassedAttr = false;
  10160. if (attrTypeDef != NULL)
  10161. {
  10162. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  10163. // We solve it by having a 'bypass' for known attributes that Object depends on
  10164. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  10165. {
  10166. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  10167. {
  10168. for (auto methodDef : attrTypeDef->mMethods)
  10169. {
  10170. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  10171. {
  10172. customAttribute.mType = attrType->ToTypeInstance();
  10173. customAttribute.mCtor = methodDef;
  10174. isBypassedAttr = true;
  10175. break;
  10176. }
  10177. }
  10178. }
  10179. }
  10180. if (isBypassedAttr)
  10181. {
  10182. customAttribute.mAwaitingValidation = false;
  10183. customAttributes->mAttributes.push_back(customAttribute);
  10184. continue;
  10185. }
  10186. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInst(mContext->mUnreifiedModule->mCurTypeInstance, mCurTypeInstance);
  10187. SetAndRestoreValue<BfMethodInstance*> prevCurMethodInst(mContext->mUnreifiedModule->mCurMethodInstance, mCurMethodInstance);
  10188. if (mContext->mCurTypeState != NULL)
  10189. {
  10190. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10191. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10192. }
  10193. else
  10194. {
  10195. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10196. }
  10197. }
  10198. BfTypeInstance* attrTypeInst = NULL;
  10199. if (attrType == NULL)
  10200. continue;
  10201. attrTypeInst = attrType->ToTypeInstance();
  10202. if ((attrTypeInst != NULL) && (attrTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting))
  10203. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  10204. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  10205. {
  10206. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  10207. continue;
  10208. }
  10209. if ((mIsReified) && (attrTypeInst->mAttributeData != NULL) && ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_ReflectAttribute) != 0))
  10210. {
  10211. // Reify attribute
  10212. PopulateType(attrTypeInst);
  10213. }
  10214. if (mCurTypeInstance != NULL)
  10215. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10216. customAttribute.mType = attrTypeInst;
  10217. bool allocatedMethodState = NULL;
  10218. defer(
  10219. {
  10220. if (allocatedMethodState)
  10221. {
  10222. delete mCurMethodState;
  10223. mCurMethodState = NULL;
  10224. }
  10225. });
  10226. if (mCurMethodState == NULL)
  10227. {
  10228. allocatedMethodState = true;
  10229. mCurMethodState = new BfMethodState();
  10230. mCurMethodState->mTempKind = BfMethodState::TempKind_Static;
  10231. }
  10232. BfConstResolver constResolver(this);
  10233. if (allowNonConstArgs)
  10234. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  10235. bool inPropSet = false;
  10236. SizedArray<BfResolvedArg, 2> argValues;
  10237. for (BfExpression* arg : attributesDirective->mArguments)
  10238. {
  10239. if (arg == NULL)
  10240. {
  10241. continue;
  10242. }
  10243. if (autoComplete != NULL)
  10244. autoComplete->mShowAttributeProperties = attrTypeInst;
  10245. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  10246. {
  10247. inPropSet = true;
  10248. if (autoComplete != NULL)
  10249. autoComplete->CheckNode(assignExpr->mLeft, true);
  10250. String findName = assignExpr->mLeft->ToString();
  10251. BfPropertyDef* bestProp = NULL;
  10252. BfTypeInstance* bestPropTypeInst = NULL;
  10253. BfFieldDef* bestField = NULL;
  10254. BfTypeInstance* bestFieldTypeInst = NULL;
  10255. auto checkTypeInst = attrTypeInst;
  10256. while (checkTypeInst != NULL)
  10257. {
  10258. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  10259. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  10260. {
  10261. if (prop->mName == findName)
  10262. {
  10263. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  10264. {
  10265. bestProp = prop;
  10266. bestPropTypeInst = checkTypeInst;
  10267. }
  10268. }
  10269. }
  10270. for (auto field : checkTypeInst->mTypeDef->mFields)
  10271. {
  10272. if (field->mName == findName)
  10273. {
  10274. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  10275. {
  10276. bestField = field;
  10277. bestFieldTypeInst = checkTypeInst;
  10278. }
  10279. }
  10280. }
  10281. if ((bestProp != NULL) || (bestField != NULL))
  10282. break;
  10283. checkTypeInst = checkTypeInst->mBaseType;
  10284. }
  10285. bool handledExpr = false;
  10286. if (bestField != NULL)
  10287. {
  10288. handledExpr = true;
  10289. if (mCompiler->mResolvePassData != NULL)
  10290. {
  10291. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  10292. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10293. {
  10294. autoComplete->mDefField = bestField;
  10295. autoComplete->mDefType = attrTypeDef;
  10296. }
  10297. }
  10298. if (bestField->mProtection != BfProtection_Public)
  10299. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10300. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10301. BfCustomAttributeSetField setField;
  10302. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  10303. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  10304. if (assignExpr->mRight != NULL)
  10305. {
  10306. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType, BfConstResolveFlag_NoActualizeValues);
  10307. if (result)
  10308. {
  10309. if (!keepConstsInModule)
  10310. CurrentAddToConstHolder(result.mValue);
  10311. setField.mParam = result;
  10312. customAttribute.mSetField.push_back(setField);
  10313. }
  10314. }
  10315. }
  10316. else if (bestProp == NULL)
  10317. {
  10318. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  10319. }
  10320. else
  10321. {
  10322. BfMethodDef* setMethod = NULL;
  10323. for (auto methodDef : bestProp->mMethods)
  10324. {
  10325. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10326. {
  10327. setMethod = methodDef;
  10328. break;
  10329. }
  10330. }
  10331. if (setMethod == NULL)
  10332. {
  10333. Fail("Property has no setter", assignExpr->mLeft);
  10334. }
  10335. else
  10336. {
  10337. if (mCompiler->mResolvePassData != NULL)
  10338. {
  10339. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  10340. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10341. {
  10342. autoComplete->mDefProp = bestProp;
  10343. autoComplete->mDefType = attrTypeDef;
  10344. }
  10345. }
  10346. handledExpr = true;
  10347. if (bestProp->mProtection != BfProtection_Public)
  10348. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10349. BfResolvedArg resolvedArg;
  10350. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10351. BfCustomAttributeSetProperty setProperty;
  10352. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  10353. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  10354. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  10355. if (methodInstance.mMethodInstance != NULL)
  10356. {
  10357. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  10358. if (assignExpr->mRight != NULL)
  10359. {
  10360. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType, BfConstResolveFlag_NoActualizeValues);
  10361. if ((result) && (!result.mType->IsVar()))
  10362. {
  10363. if (!result.mValue.IsConst())
  10364. result = GetDefaultTypedValue(result.mType);
  10365. BF_ASSERT(result.mType == propType);
  10366. if (!keepConstsInModule)
  10367. CurrentAddToConstHolder(result.mValue);
  10368. setProperty.mParam = result;
  10369. customAttribute.mSetProperties.push_back(setProperty);
  10370. }
  10371. }
  10372. }
  10373. }
  10374. }
  10375. if ((!handledExpr) && (assignExpr->mRight != NULL))
  10376. constResolver.Resolve(assignExpr->mRight, NULL, BfConstResolveFlag_NoActualizeValues);
  10377. }
  10378. else
  10379. {
  10380. if (inPropSet)
  10381. {
  10382. Fail("Named attribute argument expected", arg); // CS1016
  10383. }
  10384. BfDeferEvalChecker deferEvalChecker;
  10385. arg->Accept(&deferEvalChecker);
  10386. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  10387. BfResolvedArg resolvedArg;
  10388. resolvedArg.mExpression = arg;
  10389. if (deferParamEval)
  10390. {
  10391. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  10392. }
  10393. else
  10394. resolvedArg.mTypedValue = constResolver.Resolve(arg, NULL, BfConstResolveFlag_NoActualizeValues);
  10395. if (!inPropSet)
  10396. {
  10397. argValues.push_back(resolvedArg);
  10398. }
  10399. }
  10400. if (autoComplete != NULL)
  10401. autoComplete->mShowAttributeProperties = NULL;
  10402. }
  10403. auto wasCapturingMethodInfo = false;
  10404. if (autoComplete != NULL)
  10405. {
  10406. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  10407. if (attributesDirective->mCtorOpenParen != NULL)
  10408. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  10409. }
  10410. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, BfMethodGenericArguments());
  10411. methodMatcher.mBfEvalExprFlags = constResolver.mBfEvalExprFlags;
  10412. attrTypeDef = attrTypeInst->mTypeDef;
  10413. bool success = true;
  10414. bool isFailurePass = false;
  10415. for (int pass = 0; pass < 2; pass++)
  10416. {
  10417. bool isFailurePass = pass == 1;
  10418. for (auto checkMethod : attrTypeDef->mMethods)
  10419. {
  10420. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  10421. continue; // Don't match private default ctor if there's a user-defined one
  10422. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  10423. continue;
  10424. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  10425. continue;
  10426. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  10427. }
  10428. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  10429. break;
  10430. }
  10431. if (autoComplete != NULL)
  10432. {
  10433. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  10434. {
  10435. autoComplete->mIsCapturingMethodMatchInfo = true;
  10436. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  10437. }
  10438. else
  10439. autoComplete->mIsCapturingMethodMatchInfo = false;
  10440. }
  10441. if (methodMatcher.mBestMethodDef == NULL)
  10442. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  10443. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  10444. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  10445. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  10446. {
  10447. Fail("Custom attribute circular reference", attributesDirective);
  10448. }
  10449. if (mCurTypeInstance != NULL)
  10450. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10451. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  10452. success = false;
  10453. for (auto& arg : argValues)
  10454. {
  10455. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  10456. {
  10457. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  10458. constResolver.Resolve(expr, NULL, BfConstResolveFlag_NoActualizeValues);
  10459. }
  10460. }
  10461. // Move all those to the constHolder
  10462. if (!keepConstsInModule)
  10463. {
  10464. for (auto& ctorArg : customAttribute.mCtorArgs)
  10465. {
  10466. if (ctorArg.IsConst())
  10467. CurrentAddToConstHolder(ctorArg);
  10468. }
  10469. }
  10470. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  10471. {
  10472. targetOverride = BfAttributeTargets_ReturnValue;
  10473. if (attrTarget != BfAttributeTargets_Method)
  10474. {
  10475. 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.",
  10476. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  10477. success = false;
  10478. }
  10479. }
  10480. if ((success) && (targetOverride != (BfAttributeTargets)0))
  10481. {
  10482. if ((mCurMethodInstance != NULL) && (targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  10483. {
  10484. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  10485. if (methodInfoEx->mMethodCustomAttributes == NULL)
  10486. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  10487. if (success)
  10488. {
  10489. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  10490. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  10491. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  10492. }
  10493. }
  10494. // Mark as failed since we don't actually want to add this to the custom attributes set
  10495. success = false;
  10496. }
  10497. if (success)
  10498. {
  10499. if ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_DisallowAllowMultiple) != 0)
  10500. {
  10501. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  10502. {
  10503. if (prevCustomAttribute.mType == attrTypeInst)
  10504. {
  10505. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToCleanAttributeString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  10506. }
  10507. }
  10508. }
  10509. }
  10510. if (success)
  10511. {
  10512. customAttributes->mAttributes.push_back(customAttribute);
  10513. }
  10514. }
  10515. ValidateCustomAttributes(customAttributes, attrTarget);
  10516. }
  10517. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10518. {
  10519. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  10520. GetCustomAttributes(customAttributes, attributesDirective, attrType, flags, captureInfo);
  10521. return customAttributes;
  10522. }
  10523. BfCustomAttributes* BfModule::GetCustomAttributes(BfTypeDef* typeDef)
  10524. {
  10525. BF_ASSERT(mCompiler->IsAutocomplete());
  10526. BfAttributeTargets attrTarget;
  10527. if (typeDef->mIsDelegate)
  10528. attrTarget = BfAttributeTargets_Delegate;
  10529. else if (typeDef->mIsFunction)
  10530. attrTarget = BfAttributeTargets_Function;
  10531. else if (typeDef->mTypeCode == BfTypeCode_Enum)
  10532. attrTarget = BfAttributeTargets_Enum;
  10533. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  10534. attrTarget = BfAttributeTargets_Interface;
  10535. else if (typeDef->mTypeCode == BfTypeCode_Struct)
  10536. attrTarget = BfAttributeTargets_Struct;
  10537. else
  10538. attrTarget = BfAttributeTargets_Class;
  10539. return GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  10540. }
  10541. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  10542. {
  10543. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  10544. Warn(0, "Unused attributes", attributeState->mSrc);
  10545. }
  10546. void BfModule::ProcessTypeInstCustomAttributes(int& packing, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  10547. {
  10548. if (mCurTypeInstance->mTypeDef->mIsAlwaysInclude)
  10549. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  10550. if (mCurTypeInstance->mCustomAttributes != NULL)
  10551. {
  10552. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  10553. {
  10554. String typeName = TypeToString(customAttribute.mType);
  10555. if (typeName == "System.PackedAttribute")
  10556. {
  10557. packing = 1;
  10558. if (customAttribute.mCtorArgs.size() >= 1)
  10559. {
  10560. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10561. int checkPacking = alignConstant->mInt32;
  10562. if (((checkPacking & (checkPacking - 1)) == 0) && (packing > 0) && (packing < 256))
  10563. packing = checkPacking;
  10564. else
  10565. Fail("Packing must be a power of 2", customAttribute.GetRefNode());
  10566. }
  10567. }
  10568. else if (typeName == "System.UnionAttribute")
  10569. {
  10570. isUnion = true;
  10571. }
  10572. else if (typeName == "System.CReprAttribute")
  10573. {
  10574. isCRepr = true;
  10575. isOrdered = true;
  10576. }
  10577. else if (typeName == "System.OrderedAttribute")
  10578. {
  10579. isOrdered = true;
  10580. }
  10581. else if (typeName == "System.AlwaysIncludeAttribute")
  10582. {
  10583. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  10584. for (auto setProp : customAttribute.mSetProperties)
  10585. {
  10586. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  10587. if (propertyDef->mName == "AssumeInstantiated")
  10588. {
  10589. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10590. if ((constant != NULL) && (constant->mBool))
  10591. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_AssumeInstantiated);
  10592. }
  10593. else if (propertyDef->mName == "IncludeAllMethods")
  10594. {
  10595. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10596. if ((constant != NULL) && (constant->mBool))
  10597. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_IncludeAllMethods);
  10598. }
  10599. }
  10600. }
  10601. else if (typeName == "System.AlignAttribute")
  10602. {
  10603. if (customAttribute.mCtorArgs.size() >= 1)
  10604. {
  10605. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10606. int checkAlign = alignConstant->mInt32;
  10607. if ((checkAlign & (checkAlign - 1)) == 0)
  10608. alignOverride = checkAlign;
  10609. else
  10610. Fail("Alignment must be a power of 2", customAttribute.GetRefNode());
  10611. }
  10612. }
  10613. else if (typeName == "System.UnderlyingArrayAttribute")
  10614. {
  10615. if (customAttribute.mCtorArgs.size() >= 2)
  10616. {
  10617. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10618. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  10619. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  10620. {
  10621. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  10622. underlyingArraySize = sizeConstant->mInt32;
  10623. }
  10624. }
  10625. }
  10626. if (customAttribute.mType->mAttributeData == NULL)
  10627. PopulateType(customAttribute.mType);
  10628. BF_ASSERT(customAttribute.mType->mAttributeData != NULL);
  10629. if ((customAttribute.mType->mAttributeData != NULL) && ((customAttribute.mType->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0))
  10630. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | customAttribute.mType->mAttributeData->mAlwaysIncludeUser);
  10631. }
  10632. }
  10633. }
  10634. // Checking to see if we're an attribute or not
  10635. void BfModule::ProcessCustomAttributeData()
  10636. {
  10637. if (mCurTypeInstance->mAttributeData != NULL)
  10638. return;
  10639. bool isAttribute = false;
  10640. auto checkTypeInst = mCurTypeInstance->mBaseType;
  10641. while (checkTypeInst != NULL)
  10642. {
  10643. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  10644. isAttribute = true;
  10645. checkTypeInst = checkTypeInst->mBaseType;
  10646. }
  10647. if (!isAttribute)
  10648. return;
  10649. auto attributeData = new BfAttributeData();
  10650. bool hasCustomAttribute = false;
  10651. if (mCurTypeInstance->mCustomAttributes != NULL)
  10652. {
  10653. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  10654. {
  10655. if (customAttribute.mType->IsInstanceOf(mCompiler->mAttributeUsageAttributeTypeDef))
  10656. {
  10657. if (customAttribute.mCtorArgs.size() > 0)
  10658. {
  10659. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10660. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  10661. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  10662. }
  10663. if (customAttribute.mCtorArgs.size() == 2)
  10664. {
  10665. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10666. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  10667. {
  10668. attributeData->mFlags = (BfAttributeFlags)constant->mInt32;
  10669. }
  10670. }
  10671. for (auto& setProp : customAttribute.mSetProperties)
  10672. {
  10673. BfPropertyDef* propDef = setProp.mPropertyRef;
  10674. if (propDef->mName == "AllowMultiple")
  10675. {
  10676. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10677. if ((constant != NULL) && (constant->mBool))
  10678. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_DisallowAllowMultiple);
  10679. else
  10680. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_DisallowAllowMultiple);
  10681. }
  10682. else if (propDef->mName == "Inherited")
  10683. {
  10684. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10685. if ((constant != NULL) && (constant->mBool))
  10686. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_NotInherited);
  10687. else
  10688. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_NotInherited);
  10689. }
  10690. else if (propDef->mName == "ValidOn")
  10691. {
  10692. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10693. if (constant != NULL)
  10694. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  10695. }
  10696. else if (propDef->mName == "AlwaysIncludeUser")
  10697. {
  10698. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10699. if (constant != NULL)
  10700. attributeData->mAlwaysIncludeUser = (BfAlwaysIncludeFlags)constant->mInt32;
  10701. }
  10702. }
  10703. hasCustomAttribute = true;
  10704. }
  10705. }
  10706. }
  10707. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  10708. {
  10709. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  10710. attributeData->mFlags = mCurTypeInstance->mBaseType->mAttributeData->mFlags;
  10711. attributeData->mAlwaysIncludeUser = mCurTypeInstance->mBaseType->mAttributeData->mAlwaysIncludeUser;
  10712. }
  10713. mCurTypeInstance->mAttributeData = attributeData;
  10714. }
  10715. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  10716. {
  10717. auto constant = constHolder->GetConstant(irValue);
  10718. if (constant == NULL)
  10719. return false;
  10720. if (constant->mTypeCode != BfTypeCode_StringId)
  10721. return false;
  10722. int stringId = constant->mInt32;
  10723. BfStringPoolEntry* entry = NULL;
  10724. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  10725. {
  10726. str += entry->mString;
  10727. }
  10728. else
  10729. {
  10730. BF_DBG_FATAL("Failed to find string by id");
  10731. }
  10732. return true;
  10733. }
  10734. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  10735. {
  10736. BfVariant variant;
  10737. variant.mTypeCode = BfTypeCode_None;
  10738. BfType* primType = NULL;
  10739. if (value.mType->IsPrimitiveType())
  10740. primType = (BfPrimitiveType*)value.mType;
  10741. else if (value.mType->IsTypedPrimitive())
  10742. primType = value.mType->GetUnderlyingType();
  10743. else if (value.mType->IsInstanceOf(mCompiler->mStringTypeDef))
  10744. primType = value.mType;
  10745. if (primType)
  10746. {
  10747. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  10748. if (constant != NULL)
  10749. {
  10750. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  10751. {
  10752. variant.mUInt64 = 0;
  10753. variant.mTypeCode = BfTypeCode_Let;
  10754. return variant;
  10755. }
  10756. if (constant->mConstType == BfConstType_GlobalVar)
  10757. {
  10758. int stringIdx = GetStringPoolIdx(value.mValue, mBfIRBuilder);
  10759. if (stringIdx != -1)
  10760. {
  10761. variant.mTypeCode = BfTypeCode_StringId;
  10762. variant.mInt64 = stringIdx;
  10763. return variant;
  10764. }
  10765. }
  10766. switch (constant->mTypeCode)
  10767. {
  10768. case BfTypeCode_Boolean:
  10769. case BfTypeCode_Int8:
  10770. case BfTypeCode_UInt8:
  10771. case BfTypeCode_Int16:
  10772. case BfTypeCode_UInt16:
  10773. case BfTypeCode_Int32:
  10774. case BfTypeCode_UInt32:
  10775. case BfTypeCode_Int64:
  10776. case BfTypeCode_UInt64:
  10777. case BfTypeCode_IntPtr:
  10778. case BfTypeCode_UIntPtr:
  10779. case BfTypeCode_IntUnknown:
  10780. case BfTypeCode_UIntUnknown:
  10781. case BfTypeCode_Double:
  10782. case BfTypeCode_Char8:
  10783. case BfTypeCode_Char16:
  10784. case BfTypeCode_Char32:
  10785. case BfTypeCode_StringId:
  10786. variant.mTypeCode = constant->mTypeCode;
  10787. variant.mInt64 = constant->mInt64;
  10788. break;
  10789. case BfTypeCode_Float:
  10790. variant.mTypeCode = constant->mTypeCode;
  10791. variant.mSingle = (float)constant->mDouble;
  10792. break;
  10793. default:
  10794. if (refNode != NULL)
  10795. Fail("Invalid const expression type", refNode);
  10796. break;
  10797. }
  10798. }
  10799. }
  10800. return variant;
  10801. }
  10802. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  10803. {
  10804. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  10805. {
  10806. auto refType = (BfRefType*)typedValue.mType;
  10807. auto elementType = typedValue.mType->GetUnderlyingType();
  10808. if (typedValue.IsAddr())
  10809. {
  10810. if (elementType->IsValuelessType())
  10811. {
  10812. BF_ASSERT(!typedValue.mValue);
  10813. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  10814. }
  10815. else
  10816. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  10817. }
  10818. else
  10819. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  10820. if (typedValue.mType->IsValuelessType())
  10821. {
  10822. BF_ASSERT(typedValue.mValue.IsFake());
  10823. }
  10824. if (refType->mRefKind == BfRefType::RefKind_In)
  10825. {
  10826. if (typedValue.mKind == BfTypedValueKind_Addr)
  10827. typedValue.mKind = BfTypedValueKind_ReadOnlyAddr;
  10828. }
  10829. }
  10830. return typedValue;
  10831. }
  10832. BfTypedValue BfModule::ToRef(BfTypedValue typedValue, BfRefType* refType)
  10833. {
  10834. if (refType == NULL)
  10835. refType = CreateRefType(typedValue.mType);
  10836. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (typedValue.mType->IsObjectOrInterface()))
  10837. {
  10838. return LoadValue(typedValue);
  10839. }
  10840. if (refType->mRefKind == BfRefType::RefKind_Mut)
  10841. refType = CreateRefType(typedValue.mType);
  10842. if (!typedValue.mType->IsValuelessType())
  10843. typedValue = MakeAddressable(typedValue, false, true);
  10844. return BfTypedValue(typedValue.mValue, refType);
  10845. }
  10846. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  10847. {
  10848. if (!typedValue.IsAddr())
  10849. return typedValue;
  10850. PopulateType(typedValue.mType);
  10851. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  10852. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  10853. if (typedValue.mValue.IsConst())
  10854. {
  10855. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  10856. if (constantValue != NULL)
  10857. {
  10858. if (constantValue->mConstType == BfConstType_GlobalVar)
  10859. {
  10860. auto globalVar = (BfGlobalVar*)constantValue;
  10861. if (globalVar->mName[0] == '#')
  10862. {
  10863. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  10864. if (result)
  10865. {
  10866. // We want to avoid 'unreachable code' issues from values that
  10867. // are technically constant but change depending on compilation context
  10868. if (mCurMethodState != NULL)
  10869. {
  10870. auto checkScope = mCurMethodState->mCurScope;
  10871. while (checkScope != NULL)
  10872. {
  10873. checkScope->mSupressNextUnreachable = true;
  10874. checkScope = checkScope->mPrevScope;
  10875. }
  10876. }
  10877. return result;
  10878. }
  10879. return GetDefaultTypedValue(typedValue.mType);
  10880. }
  10881. }
  10882. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  10883. {
  10884. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  10885. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  10886. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  10887. auto ceTypedValue = ceDebugger->GetAddr(constantValue);
  10888. if (ceTypedValue)
  10889. {
  10890. if ((typedValue.mType->IsObjectOrInterface()) || (typedValue.mType->IsPointer()) || (typedValue.mType->IsRef()))
  10891. {
  10892. void* data = ceContext->GetMemoryPtr((addr_ce)ceTypedValue.mAddr, sizeof(addr_ce));
  10893. if (data == NULL)
  10894. {
  10895. Fail("Invalid address", refNode);
  10896. return GetDefaultTypedValue(typedValue.mType);
  10897. }
  10898. uint64 dataAddr;
  10899. if (mSystem->mPtrSize == 4)
  10900. dataAddr = *(uint32*)data;
  10901. else
  10902. dataAddr = *(uint64*)data;
  10903. return BfTypedValue(mBfIRBuilder->CreateIntToPtr(
  10904. mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataAddr), mBfIRBuilder->MapType(typedValue.mType)), typedValue.mType);
  10905. }
  10906. auto constVal = ceContext->CreateConstant(this, ceContext->mMemory.mVals + ceTypedValue.mAddr, typedValue.mType);
  10907. if (!constVal)
  10908. {
  10909. Fail("Failed to create const", refNode);
  10910. return GetDefaultTypedValue(typedValue.mType);
  10911. }
  10912. return BfTypedValue(constVal, typedValue.mType);
  10913. }
  10914. }
  10915. }
  10916. }
  10917. BfIRValue loadedVal = typedValue.mValue;
  10918. if (loadedVal)
  10919. {
  10920. if (typedValue.mType->IsVar())
  10921. {
  10922. return BfTypedValue(loadedVal, typedValue.mType, false);
  10923. }
  10924. /*if (isVolatile)
  10925. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  10926. PopulateType(typedValue.mType, BfPopulateType_Data);
  10927. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  10928. }
  10929. return BfTypedValue(loadedVal, typedValue.mType, false);
  10930. }
  10931. BfTypedValue BfModule::PrepareConst(BfTypedValue& typedValue)
  10932. {
  10933. if (!typedValue.mValue.IsConst())
  10934. return typedValue;
  10935. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  10936. if (constant->mTypeCode == BfTypeCode_StringId)
  10937. return GetTypedValueFromConstant(constant, mBfIRBuilder, typedValue.mType);
  10938. return typedValue;
  10939. }
  10940. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  10941. {
  10942. if (typedValue.IsSplat())
  10943. return AggregateSplat(typedValue);
  10944. if (typedValue.IsAddr())
  10945. return LoadValue(typedValue);
  10946. return typedValue;
  10947. }
  10948. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  10949. {
  10950. if (!typedValue.IsSplat())
  10951. return typedValue;
  10952. BF_ASSERT(!mIsComptimeModule);
  10953. if (typedValue.mType->IsValuelessType())
  10954. return typedValue;
  10955. int elementIdx = 0;
  10956. auto _ExtractValue = [&](BfType* checkType)
  10957. {
  10958. if (valueArrPtr != NULL)
  10959. return valueArrPtr[elementIdx++];
  10960. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  10961. };
  10962. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  10963. {
  10964. if (checkType->IsStruct())
  10965. {
  10966. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  10967. auto checkTypeInstance = checkType->ToTypeInstance();
  10968. if (checkTypeInstance->mBaseType != NULL)
  10969. {
  10970. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  10971. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  10972. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  10973. }
  10974. if (checkTypeInstance->mIsUnion)
  10975. {
  10976. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  10977. if (!unionInnerType->IsValuelessType())
  10978. {
  10979. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  10980. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  10981. }
  10982. if (checkTypeInstance->IsEnum())
  10983. {
  10984. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  10985. BfIRValue fieldValue = checkTypeLambda(dscrType);
  10986. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  10987. }
  10988. }
  10989. else
  10990. {
  10991. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  10992. {
  10993. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  10994. if (fieldInstance->mDataIdx >= 0)
  10995. {
  10996. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  10997. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  10998. }
  10999. }
  11000. }
  11001. return curValue;
  11002. }
  11003. else if (checkType->IsMethodRef())
  11004. {
  11005. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11006. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11007. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11008. {
  11009. BfIRValue fieldValue;
  11010. auto checkType = methodRefType->GetCaptureType(dataIdx);
  11011. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11012. {
  11013. fieldValue = checkTypeLambda(checkType);
  11014. }
  11015. else
  11016. {
  11017. fieldValue = _ExtractValue(checkType);
  11018. }
  11019. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  11020. }
  11021. return curValue;
  11022. }
  11023. else if (!checkType->IsValuelessType())
  11024. {
  11025. return _ExtractValue(checkType);
  11026. }
  11027. return BfIRValue();
  11028. };
  11029. BfIRValue value = checkTypeLambda(typedValue.mType);
  11030. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  11031. }
  11032. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  11033. {
  11034. if (!typedValue.IsSplat())
  11035. return;
  11036. if (typedValue.mType->IsValuelessType())
  11037. return;
  11038. BF_ASSERT(!mIsComptimeModule);
  11039. /*static int sCallIdx = 0;
  11040. if (!mCompiler->mIsResolveOnly)
  11041. sCallIdx++;
  11042. int callIdx = sCallIdx;*/
  11043. int elementIdx = 0;
  11044. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  11045. {
  11046. if (checkType->IsStruct())
  11047. {
  11048. auto checkTypeInstance = checkType->ToTypeInstance();
  11049. if (checkTypeInstance->mBaseType != NULL)
  11050. {
  11051. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  11052. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  11053. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  11054. }
  11055. if (checkTypeInstance->mIsUnion)
  11056. {
  11057. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11058. if (!unionInnerType->IsValuelessType())
  11059. {
  11060. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  11061. checkTypeLambda(unionInnerType, fieldAddrVal);
  11062. }
  11063. if (checkTypeInstance->IsEnum())
  11064. {
  11065. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11066. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  11067. checkTypeLambda(dscrType, fieldAddrVal);
  11068. }
  11069. }
  11070. else
  11071. {
  11072. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11073. {
  11074. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11075. if (fieldInstance->mDataIdx >= 0)
  11076. {
  11077. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  11078. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  11079. }
  11080. }
  11081. }
  11082. }
  11083. else if (checkType->IsMethodRef())
  11084. {
  11085. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11086. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11087. {
  11088. auto dataType = methodRefType->GetCaptureType(dataIdx);
  11089. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  11090. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11091. {
  11092. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  11093. }
  11094. else
  11095. {
  11096. // static int sItrCount = 0;
  11097. // sItrCount++;
  11098. // int curItr = sItrCount;
  11099. // if (curItr == 1)
  11100. // {
  11101. // NOP;
  11102. // }
  11103. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  11104. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  11105. }
  11106. }
  11107. }
  11108. else if (!checkType->IsValuelessType())
  11109. {
  11110. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  11111. mBfIRBuilder->CreateStore(val, curAddrVal);
  11112. }
  11113. };
  11114. checkTypeLambda(typedValue.mType, addrVal);
  11115. }
  11116. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal, bool forceMutable, bool forceAddressable)
  11117. {
  11118. bool wasReadOnly = typedVal.IsReadOnly();
  11119. if ((forceAddressable) ||
  11120. ((typedVal.mType->IsValueType()) &&
  11121. (!typedVal.mType->IsValuelessType())))
  11122. {
  11123. wasReadOnly = true; // Any non-addr is implicitly read-only
  11124. //static int gCallIdx = 0;
  11125. FixValueActualization(typedVal);
  11126. if (typedVal.IsAddr())
  11127. return typedVal;
  11128. BfType* type = typedVal.mType;
  11129. PopulateType(type);
  11130. BfIRValue tempVar;
  11131. if (typedVal.mValue.IsFake())
  11132. tempVar = mBfIRBuilder->GetFakeVal();
  11133. else
  11134. {
  11135. tempVar = CreateAlloca(type);
  11136. if (typedVal.IsSplat())
  11137. AggregateSplatIntoAddr(typedVal, tempVar);
  11138. else
  11139. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  11140. }
  11141. if (forceMutable)
  11142. wasReadOnly = false;
  11143. return BfTypedValue(tempVar, type,
  11144. typedVal.IsThis() ?
  11145. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  11146. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  11147. }
  11148. return LoadValue(typedVal);
  11149. }
  11150. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  11151. {
  11152. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  11153. typedValue.mKind = BfTypedValueKind_Addr;
  11154. return typedValue;
  11155. }
  11156. BfTypedValue BfModule::CopyValue(const BfTypedValue& typedValue)
  11157. {
  11158. return MakeAddressable(LoadValue(typedValue), true);
  11159. }
  11160. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  11161. {
  11162. BF_ASSERT(!mIsComptimeModule);
  11163. BfIRValue val;
  11164. if (typedValue.mValue.IsArg())
  11165. {
  11166. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  11167. if (isAddr != NULL)
  11168. {
  11169. if (wantType != NULL)
  11170. *isAddr = wantType->IsComposite();
  11171. else
  11172. *isAddr = false;
  11173. }
  11174. else if (wantType->IsComposite())
  11175. val = mBfIRBuilder->CreateLoad(val);
  11176. }
  11177. if (!val)
  11178. {
  11179. auto checkMethodState = mCurMethodState;
  11180. while (checkMethodState != NULL)
  11181. {
  11182. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  11183. {
  11184. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  11185. if (decompAddr == typedValue.mValue)
  11186. {
  11187. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  11188. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  11189. {
  11190. // This is really backing for a POINTER to a composite inside a methodRef
  11191. val = mBfIRBuilder->CreateLoad(val);
  11192. }
  11193. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  11194. {
  11195. *isAddr = true;
  11196. return val;
  11197. }
  11198. else
  11199. {
  11200. val = mBfIRBuilder->CreateLoad(val);
  11201. break;
  11202. }
  11203. }
  11204. }
  11205. if (val)
  11206. break;
  11207. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  11208. {
  11209. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  11210. return mBfIRBuilder->GetFakeVal();
  11211. }
  11212. checkMethodState = checkMethodState->mPrevMethodState;
  11213. }
  11214. }
  11215. if (val)
  11216. {
  11217. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  11218. {
  11219. BF_ASSERT(wantType != NULL);
  11220. if (wantType != NULL)
  11221. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  11222. }
  11223. return val;
  11224. }
  11225. BFMODULE_FATAL(this, "Splat not found");
  11226. return BfIRValue();
  11227. }
  11228. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  11229. {
  11230. int useFieldIdx = fieldIdx;
  11231. BfType* fieldType = NULL;
  11232. if (fieldInstance != NULL)
  11233. {
  11234. fieldType = fieldInstance->mResolvedType;
  11235. if (typedValue.mType->IsUnion())
  11236. {
  11237. if (fieldIdx == 1)
  11238. {
  11239. if (typedValue.IsSplat())
  11240. {
  11241. BfTypedValue innerVal = typedValue;
  11242. innerVal.mType = fieldType;
  11243. return innerVal;
  11244. }
  11245. }
  11246. }
  11247. }
  11248. else
  11249. {
  11250. if (typedValue.mType->IsPayloadEnum())
  11251. {
  11252. auto typeInst = typedValue.mType->ToTypeInstance();
  11253. if (fieldIdx == 1)
  11254. fieldType = typeInst->GetUnionInnerType();
  11255. else if (fieldIdx == 2)
  11256. {
  11257. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  11258. }
  11259. }
  11260. else if (typedValue.mType->IsUnion())
  11261. {
  11262. if (fieldIdx == 1)
  11263. {
  11264. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  11265. if (typedValue.IsSplat())
  11266. {
  11267. BfTypedValue innerVal = typedValue;
  11268. innerVal.mType = fieldType;
  11269. return innerVal;
  11270. }
  11271. }
  11272. }
  11273. }
  11274. BF_ASSERT(typedValue.mType->IsStruct());
  11275. if (typedValue.IsSplat())
  11276. {
  11277. if (typedValue.mType->IsPayloadEnum())
  11278. {
  11279. if (fieldIdx == 1)
  11280. {
  11281. // Payload
  11282. auto typeInst = typedValue.mType->ToTypeInstance();
  11283. auto unionInnerType = typeInst->GetUnionInnerType();
  11284. bool isAddr = false;
  11285. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  11286. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  11287. }
  11288. if (fieldIdx == 2)
  11289. {
  11290. // Discriminator
  11291. auto typeInst = typedValue.mType->ToTypeInstance();
  11292. auto unionInnerType = typeInst->GetUnionInnerType();
  11293. auto dscrType = typeInst->GetDiscriminatorType();
  11294. int argIdx = typedValue.mValue.mId;
  11295. int componentIdx = 0;
  11296. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  11297. bool isAddr;
  11298. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  11299. return BfTypedValue(irVal, dscrType, isAddr);
  11300. }
  11301. }
  11302. int componentIdx = 0;
  11303. BfTypedValue retVal;
  11304. BfFieldInstance* wantFieldInstance = fieldInstance;
  11305. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11306. {
  11307. if (checkType->IsStruct())
  11308. {
  11309. auto checkTypeInstance = checkType->ToTypeInstance();
  11310. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  11311. {
  11312. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  11313. fieldType = checkTypeInstance->GetUnionInnerType();
  11314. checkTypeLambda(fieldType);
  11315. if (checkType->IsEnum())
  11316. {
  11317. // Past discriminator...
  11318. componentIdx++;
  11319. }
  11320. return;
  11321. }
  11322. if (checkTypeInstance->mBaseType != NULL)
  11323. checkTypeLambda(checkTypeInstance->mBaseType);
  11324. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11325. {
  11326. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11327. if (fieldInstance == wantFieldInstance)
  11328. {
  11329. if (fieldInstance->mResolvedType->IsValuelessType())
  11330. {
  11331. retVal = GetDefaultTypedValue(fieldInstance->mResolvedType);
  11332. break;
  11333. }
  11334. bool isAddr = false;
  11335. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  11336. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  11337. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  11338. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  11339. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  11340. {
  11341. retVal = LoadValue(retVal);
  11342. }
  11343. break;
  11344. }
  11345. if (fieldInstance->mDataIdx >= 0)
  11346. checkTypeLambda(fieldInstance->GetResolvedType());
  11347. }
  11348. }
  11349. else if (!checkType->IsValuelessType())
  11350. {
  11351. componentIdx++;
  11352. //argIdx++;
  11353. }
  11354. };
  11355. checkTypeLambda(typedValue.mType);
  11356. BF_ASSERT(retVal);
  11357. return retVal;
  11358. }
  11359. if (typedValue.IsAddr())
  11360. {
  11361. BF_ASSERT(fieldType != NULL);
  11362. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  11363. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  11364. }
  11365. else
  11366. {
  11367. BF_ASSERT(fieldType != NULL);
  11368. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  11369. }
  11370. }
  11371. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  11372. {
  11373. if (typedValue.IsAddr())
  11374. {
  11375. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  11376. return mBfIRBuilder->CreateLoad(addrVal);
  11377. }
  11378. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  11379. }
  11380. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  11381. {
  11382. if (isElementIndex)
  11383. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11384. else
  11385. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11386. // if (elementType->IsSizeAligned())
  11387. // {
  11388. // if (isElementIndex)
  11389. // return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11390. // else
  11391. // return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11392. // }
  11393. //
  11394. // auto ptrType = CreatePointerType(elementType);
  11395. // auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  11396. // auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  11397. // auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  11398. // BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  11399. // BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  11400. // return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  11401. }
  11402. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  11403. {
  11404. if (elementType->IsSizeAligned())
  11405. {
  11406. if (isElementIndex)
  11407. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  11408. else
  11409. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11410. }
  11411. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  11412. }
  11413. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  11414. {
  11415. if (modifyType == NULL)
  11416. modifyType = "modify";
  11417. if (typedValue.mType->IsVar())
  11418. return true;
  11419. if (typedValue.IsReadOnly())
  11420. {
  11421. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  11422. return false;
  11423. }
  11424. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  11425. {
  11426. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  11427. return false;
  11428. }
  11429. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  11430. {
  11431. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  11432. return false;
  11433. }
  11434. return true;
  11435. }
  11436. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  11437. {
  11438. // If one is an interface and the other is an impl, B is the impl
  11439. auto implOwner = methodB->GetOwner();
  11440. if (methodA->mMethodDef->mIsLocalMethod)
  11441. {
  11442. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  11443. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  11444. if (sepPosA != sepPosB)
  11445. return false;
  11446. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  11447. return false;
  11448. }
  11449. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  11450. return false;
  11451. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  11452. return false;
  11453. if (methodA->mMethodDef->mHasComptime != methodB->mMethodDef->mHasComptime)
  11454. return false;
  11455. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  11456. return false;
  11457. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  11458. {
  11459. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  11460. return false;
  11461. }
  11462. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  11463. {
  11464. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  11465. return false;
  11466. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  11467. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  11468. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  11469. return false;
  11470. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  11471. return false;
  11472. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  11473. return false;
  11474. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  11475. {
  11476. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  11477. return false;
  11478. }
  11479. }
  11480. int implicitParamCountA = methodA->GetImplicitParamCount();
  11481. int implicitParamCountB = methodB->GetImplicitParamCount();
  11482. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  11483. return false;
  11484. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  11485. return false;
  11486. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  11487. {
  11488. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  11489. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  11490. return false;
  11491. }
  11492. // Compare generic params. Generic params are part of the method signature here
  11493. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  11494. return false;
  11495. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  11496. {
  11497. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  11498. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  11499. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  11500. return false;
  11501. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  11502. return false;
  11503. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  11504. return false;
  11505. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  11506. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  11507. return false;
  11508. }
  11509. return true;
  11510. }
  11511. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  11512. {
  11513. if (!CompareMethodSignatures(methodA, methodB))
  11514. return false;
  11515. if (methodA->mReturnType != methodB->mReturnType)
  11516. return false;
  11517. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  11518. return false;
  11519. return true;
  11520. }
  11521. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  11522. {
  11523. if ((iMethodInst->GetNumGenericParams() != 0) || (methodInstance->GetNumGenericParams() != 0))
  11524. return false;
  11525. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  11526. return false;
  11527. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  11528. return false;
  11529. if (iMethodInst->mMethodDef->mIsOperator)
  11530. {
  11531. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  11532. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  11533. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  11534. return false;
  11535. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  11536. return false;
  11537. }
  11538. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  11539. return false;
  11540. auto selfType = methodInstance->GetOwner();
  11541. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  11542. {
  11543. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  11544. return false;
  11545. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  11546. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  11547. iParamType = ResolveSelfType(iParamType, selfType);
  11548. methodParamType = ResolveSelfType(methodParamType, selfType);
  11549. if (!iParamType->IsGenericParam())
  11550. {
  11551. if (methodParamType != iParamType)
  11552. return false;
  11553. }
  11554. else
  11555. {
  11556. if (!methodParamType->IsGenericParam())
  11557. return false;
  11558. auto genericParamType = (BfGenericParamType*)methodParamType;
  11559. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  11560. return false;
  11561. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  11562. bool hadInterface = false;
  11563. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  11564. if (interfaceConstraint == iParamType)
  11565. hadInterface = true;
  11566. if (!hadInterface)
  11567. return false;
  11568. }
  11569. }
  11570. return true;
  11571. }
  11572. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  11573. {
  11574. BfMethodInstance* methodInstance = methodRef;
  11575. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  11576. {
  11577. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  11578. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  11579. {
  11580. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  11581. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  11582. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  11583. BfMethodRef methodRef = methodInstance;
  11584. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  11585. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  11586. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  11587. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  11588. (mIsReified))
  11589. {
  11590. specializedMethodRefInfo->mHasReifiedRef = true;
  11591. }
  11592. }
  11593. }
  11594. }
  11595. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  11596. {
  11597. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  11598. return BfModuleMethodInstance(methodInstance, BfIRValue());
  11599. if (mBfIRBuilder == NULL)
  11600. return BfModuleMethodInstance(methodInstance, BfIRValue());
  11601. if (methodInstance->GetOwner()->IsFunction())
  11602. {
  11603. // No actual ref needed- not an actual generated function
  11604. return BfModuleMethodInstance(methodInstance, BfIRValue());
  11605. }
  11606. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  11607. if (!isGenFunction)
  11608. AddMethodReference(methodInstance, flags);
  11609. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  11610. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  11611. if (IsSkippingExtraResolveChecks())
  11612. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  11613. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  11614. {
  11615. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  11616. }
  11617. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  11618. if ((methodInstance->mIsIntrinsic) || (methodInstance->mMethodDef->mIsExtern))
  11619. isInlined = false;
  11620. BfMethodRef methodRef = methodInstance;
  11621. if (isInlined)
  11622. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  11623. else
  11624. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  11625. if (!isGenFunction)
  11626. {
  11627. BfIRValue* irFuncPtr = NULL;
  11628. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  11629. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  11630. }
  11631. if (mAwaitingInitFinish)
  11632. FinishInit();
  11633. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  11634. if (!isGenFunction)
  11635. {
  11636. BF_ASSERT(func || methodInstance->mMethodInstanceGroup->mOwner->IsInterface());
  11637. mFuncReferences[methodRef] = func;
  11638. }
  11639. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  11640. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  11641. {
  11642. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  11643. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  11644. // type instance
  11645. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  11646. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  11647. for (auto ownedTypeInst : mOwnedTypeInstances)
  11648. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  11649. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  11650. {
  11651. mIncompleteMethodCount++;
  11652. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  11653. inlineMethodRequest->mType = methodInstance->GetOwner();
  11654. inlineMethodRequest->mFromModule = this;
  11655. inlineMethodRequest->mFunc = func;
  11656. inlineMethodRequest->mFromModuleRevision = mRevision;
  11657. inlineMethodRequest->mMethodInstance = methodInstance;
  11658. BF_ASSERT(mIsModuleMutable);
  11659. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  11660. }
  11661. }
  11662. return BfModuleMethodInstance(methodInstance, func);
  11663. }
  11664. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  11665. {
  11666. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  11667. if (mBfIRBuilder == NULL)
  11668. {
  11669. // To allow for custom attribute data
  11670. PrepareForIRWriting(typeInst);
  11671. }
  11672. BfModule* declareModule = this;
  11673. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  11674. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  11675. declareModule = declareModule->mParentModule;
  11676. // Check for attributes
  11677. if (typeInst == mContext->mBfObjectType)
  11678. {
  11679. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  11680. if (methodDecl != NULL)
  11681. {
  11682. auto attributesDirective = methodDecl->mAttributes;
  11683. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  11684. {
  11685. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  11686. sourceClassifier->VisitChild(attributesDirective);
  11687. }
  11688. }
  11689. }
  11690. else
  11691. {
  11692. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  11693. GetMethodCustomAttributes(methodInstance);
  11694. }
  11695. BF_ASSERT(mModuleOptions == NULL);
  11696. if (methodInstance->GetCustomAttributes() != NULL)
  11697. {
  11698. auto project = typeInst->mTypeDef->mProject;
  11699. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  11700. BfModuleOptions wantOptions = moduleOptions;
  11701. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  11702. if (typeOptions != NULL)
  11703. {
  11704. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  11705. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  11706. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  11707. }
  11708. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  11709. {
  11710. StringT<128> attrName;
  11711. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  11712. {
  11713. attrName.Clear();
  11714. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  11715. Array<int>* arrPtr;
  11716. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  11717. {
  11718. for (auto optionsIdx : *arrPtr)
  11719. {
  11720. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  11721. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  11722. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  11723. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  11724. }
  11725. }
  11726. }
  11727. }
  11728. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  11729. {
  11730. auto lastCheckModule = this;
  11731. auto checkModule = this->mNextAltModule;
  11732. while (checkModule != NULL)
  11733. {
  11734. if (*checkModule->mModuleOptions == wantOptions)
  11735. {
  11736. declareModule = checkModule;
  11737. break;
  11738. }
  11739. lastCheckModule = checkModule;
  11740. checkModule = checkModule->mNextAltModule;
  11741. }
  11742. // Not found?
  11743. if (declareModule == this)
  11744. {
  11745. String specModuleName = mModuleName + "@@";
  11746. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  11747. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  11748. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  11749. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  11750. declareModule = new BfModule(mContext, specModuleName);
  11751. declareModule->mProject = project;
  11752. declareModule->mModuleOptions = new BfModuleOptions();
  11753. *declareModule->mModuleOptions = wantOptions;
  11754. declareModule->mParentModule = lastCheckModule;
  11755. declareModule->Init();
  11756. lastCheckModule->mNextAltModule = declareModule;
  11757. }
  11758. }
  11759. }
  11760. declareModule->PrepareForIRWriting(typeInst);
  11761. return declareModule;
  11762. }
  11763. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  11764. {
  11765. if (methodDef->mMethodType == BfMethodType_Init)
  11766. return BfModuleMethodInstance();
  11767. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  11768. {
  11769. // Don't bother inlining for resolve-only
  11770. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  11771. }
  11772. if (methodDef->mIsExtern)
  11773. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  11774. bool processNow = false;
  11775. bool keepInCurrentModule = false;
  11776. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  11777. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  11778. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  11779. {
  11780. return BfModuleMethodInstance();
  11781. }
  11782. if (methodDef->mIsLocalMethod)
  11783. {
  11784. auto rootMethodState = mCurMethodState->GetRootMethodState();
  11785. BfLocalMethod* localMethod;
  11786. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  11787. {
  11788. // Handle the def in the correct method state
  11789. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  11790. }
  11791. BFMODULE_FATAL(this, "Cannot find local method");
  11792. return BfModuleMethodInstance();
  11793. }
  11794. #ifdef _DEBUG
  11795. for (auto arg : methodGenericArguments)
  11796. BF_ASSERT(!arg->IsVar());
  11797. #endif
  11798. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  11799. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  11800. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  11801. // a FinishInit
  11802. if ((typeInst->IsIncomplete()) &&
  11803. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  11804. {
  11805. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  11806. // for resolve-only because we don't differentiate between reified/unreified there
  11807. if ((methodDef->mIsStatic) /*&& (mIsComptimeModule)*/)
  11808. {
  11809. if (!typeInst->DefineStateAllowsStaticMethods())
  11810. PopulateType(typeInst, BfPopulateType_AllowStaticMethods);
  11811. }
  11812. else
  11813. PopulateType(typeInst, BfPopulateType_Full);
  11814. if (typeInst->mDefineState < BfTypeDefineState_Defined)
  11815. {
  11816. if (!mCompiler->EnsureCeUnpaused(typeInst))
  11817. {
  11818. BfLogSysM("GetMethodInstance (DefineState < BfTypeDefineState_Defined)) bailing due to IsCePaused\n");
  11819. return BfModuleMethodInstance();
  11820. }
  11821. }
  11822. }
  11823. bool tryModuleMethodLookup = false;
  11824. BfModuleMethodInstance moduleMethodInst;
  11825. BfModule* instModule = typeInst->mModule;
  11826. if (keepInCurrentModule)
  11827. {
  11828. // Stay here
  11829. instModule = this;
  11830. }
  11831. if (this == mContext->mUnreifiedModule)
  11832. {
  11833. // Stay in this 'resolve only' module here
  11834. }
  11835. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  11836. {
  11837. BF_ASSERT(this == mContext->mUnreifiedModule);
  11838. }
  11839. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  11840. {
  11841. BF_ASSERT(instModule == mParentModule);
  11842. }
  11843. else if (instModule != this)
  11844. {
  11845. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  11846. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  11847. if ((!mIsComptimeModule) && (!mIsReified) && (instModule->mIsReified))
  11848. {
  11849. BF_ASSERT(!mCompiler->mIsResolveOnly);
  11850. // A resolve-only module is specializing a method from a type in a reified module,
  11851. // we need to take care that this doesn't cause anything new to become reified
  11852. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  11853. if (!moduleMethodInstance)
  11854. return moduleMethodInstance;
  11855. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  11856. return moduleMethodInstance;
  11857. }
  11858. else
  11859. {
  11860. if ((!mIsComptimeModule) && (mIsReified) && (!instModule->mIsReified))
  11861. {
  11862. if (!typeInst->IsUnspecializedType())
  11863. {
  11864. if (!instModule->mReifyQueued)
  11865. {
  11866. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  11867. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  11868. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  11869. mContext->mReifyModuleWorkList.Add(instModule);
  11870. instModule->mReifyQueued = true;
  11871. }
  11872. // This ensures that the method will actually be created when it gets reified
  11873. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  11874. specializationRequest->mFromModule = typeInst->mModule;
  11875. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  11876. specializationRequest->Init(typeInst, foreignType, methodDef);
  11877. //specializationRequest->mMethodDef = methodDef;
  11878. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  11879. specializationRequest->mType = typeInst;
  11880. specializationRequest->mFlags = flags;
  11881. }
  11882. }
  11883. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  11884. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoReference);
  11885. if (mIsComptimeModule)
  11886. {
  11887. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  11888. if (!mCompiler->mIsResolveOnly)
  11889. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification | BfGetMethodInstanceFlag_Unreified | BfGetMethodInstanceFlag_MethodInstanceOnly);
  11890. }
  11891. // Not extern
  11892. // Create the instance in the proper module and then create a reference in this one
  11893. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  11894. if (!moduleMethodInst)
  11895. return moduleMethodInst;
  11896. tryModuleMethodLookup = true;
  11897. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  11898. {
  11899. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  11900. }
  11901. }
  11902. }
  11903. if (tryModuleMethodLookup)
  11904. {
  11905. SetMethodDependency(moduleMethodInst.mMethodInstance);
  11906. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  11907. }
  11908. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  11909. {
  11910. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  11911. if (moduleMethodInstance)
  11912. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  11913. return moduleMethodInst;
  11914. }
  11915. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  11916. bool hadConcreteInterfaceGenericArgument = false;
  11917. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  11918. isReified = false;
  11919. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  11920. {
  11921. isReified = false;
  11922. }
  11923. BfTypeVector sanitizedMethodGenericArguments;
  11924. SizedArray<BfProject*, 4> projectList;
  11925. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  11926. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  11927. isUnspecializedPass = false;
  11928. // 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
  11929. bool isExternalExtensionMethod = false;
  11930. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  11931. {
  11932. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) &&
  11933. (methodDef->mDeclaringType != NULL) &&
  11934. (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  11935. {
  11936. auto specProject = methodDef->mDeclaringType->mProject;
  11937. isExternalExtensionMethod = true;
  11938. if (typeInst->IsGenericTypeInstance())
  11939. {
  11940. auto genericTypeInst = (BfTypeInstance*)typeInst;
  11941. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  11942. genericTypeInst->GenerateProjectsReferenced();
  11943. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  11944. {
  11945. // This is a generic type where a generic param is already confined to the project in question
  11946. isExternalExtensionMethod = false;
  11947. }
  11948. }
  11949. if (isExternalExtensionMethod)
  11950. {
  11951. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  11952. projectList.push_back(methodDef->mDeclaringType->mProject);
  11953. }
  11954. }
  11955. }
  11956. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  11957. {
  11958. int typeProjectsCounts = 0;
  11959. if (typeInst->IsGenericTypeInstance())
  11960. {
  11961. auto genericTypeInst = (BfTypeInstance*)typeInst;
  11962. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  11963. genericTypeInst->GenerateProjectsReferenced();
  11964. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  11965. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  11966. }
  11967. else
  11968. {
  11969. typeProjectsCounts = 1;
  11970. projectList.Insert(0, typeInst->mTypeDef->mProject);
  11971. }
  11972. isUnspecializedPass = true;
  11973. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  11974. {
  11975. auto genericArgType = methodGenericArguments[genericArgIdx];
  11976. //BF_ASSERT(!genericArgType->IsRef());
  11977. if (genericArgType->IsConcreteInterfaceType())
  11978. {
  11979. hadConcreteInterfaceGenericArgument = true;
  11980. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  11981. genericArgType = concreteInterfaceType->mInterface;
  11982. }
  11983. if (genericArgType->IsGenericParam())
  11984. {
  11985. auto genericParam = (BfGenericParamType*) genericArgType;
  11986. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  11987. isUnspecializedPass = false;
  11988. }
  11989. else
  11990. {
  11991. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  11992. isUnspecializedPass = false;
  11993. }
  11994. sanitizedMethodGenericArguments.push_back(genericArgType);
  11995. }
  11996. if ((int)projectList.size() > typeProjectsCounts)
  11997. {
  11998. // Just leave the new items
  11999. projectList.RemoveRange(0, typeProjectsCounts);
  12000. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  12001. {
  12002. return lhs->mName < rhs->mName;
  12003. });
  12004. }
  12005. else
  12006. {
  12007. projectList.Clear();
  12008. }
  12009. }
  12010. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  12011. BfMethodInstanceGroup* methodInstGroup = NULL;
  12012. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12013. {
  12014. BF_ASSERT(!typeInst->IsInterface());
  12015. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  12016. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  12017. {
  12018. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  12019. // if (checkGroup.mDefault == NULL)
  12020. // {
  12021. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  12022. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  12023. // methodInstGroup = &checkGroup;
  12024. // break;
  12025. // }
  12026. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  12027. {
  12028. methodInstGroup = &checkGroup;
  12029. break;
  12030. }
  12031. }
  12032. if (methodInstGroup == NULL)
  12033. {
  12034. if (lookupMethodGenericArguments.size() != 0)
  12035. {
  12036. BF_ASSERT((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0);
  12037. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12038. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12039. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12040. }
  12041. else
  12042. {
  12043. // Allocate a new entry
  12044. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  12045. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  12046. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  12047. methodInstGroup->mOwner = typeInst;
  12048. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12049. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12050. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  12051. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12052. else
  12053. {
  12054. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  12055. mOnDemandMethodCount++;
  12056. }
  12057. }
  12058. }
  12059. }
  12060. else
  12061. {
  12062. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  12063. }
  12064. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12065. {
  12066. if (typeInst->mDefineState > BfTypeDefineState_DefinedAndMethodsSlotted)
  12067. {
  12068. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  12069. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12070. }
  12071. }
  12072. BfIRFunction prevIRFunc;
  12073. bool doingRedeclare = false;
  12074. BfMethodInstance* methodInstance = NULL;
  12075. auto _SetReified = [&]()
  12076. {
  12077. methodInstance->mIsReified = true;
  12078. };
  12079. if (lookupMethodGenericArguments.size() == 0)
  12080. {
  12081. methodInstance = methodInstGroup->mDefault;
  12082. if ((methodInstance != NULL) && ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0))
  12083. return methodInstance;
  12084. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  12085. {
  12086. MarkDerivedDirty(typeInst);
  12087. if (!HasCompiledOutput())
  12088. {
  12089. BfLogSysM("Marking non-compiled-output module method instance as reified: %p\n", methodInstance);
  12090. _SetReified();
  12091. CheckHotMethod(methodInstance, "");
  12092. }
  12093. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  12094. {
  12095. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  12096. // the specializations to handle that for us
  12097. return BfModuleMethodInstance(methodInstance);
  12098. }
  12099. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  12100. {
  12101. if (methodDef->mIsAbstract)
  12102. {
  12103. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12104. _SetReified();
  12105. }
  12106. else
  12107. {
  12108. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12109. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  12110. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  12111. doingRedeclare = true;
  12112. mOnDemandMethodCount++;
  12113. VerifyOnDemandMethods();
  12114. }
  12115. }
  12116. else
  12117. {
  12118. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  12119. // We haven't processed it yet
  12120. _SetReified();
  12121. CheckHotMethod(methodInstance, "");
  12122. if (methodInstance->mDeclModule == this)
  12123. {
  12124. if (methodInstance->mMethodProcessRequest != NULL)
  12125. {
  12126. // Disconnect method process request
  12127. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  12128. }
  12129. }
  12130. else
  12131. {
  12132. if (methodInstance->mMethodProcessRequest != NULL)
  12133. {
  12134. // Disconnect method process request
  12135. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  12136. methodInstance->mMethodProcessRequest = NULL;
  12137. }
  12138. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  12139. {
  12140. // Add new request in proper module
  12141. methodInstance->mDeclModule = this;
  12142. }
  12143. else
  12144. {
  12145. if (methodInstance->mDeclModule == NULL)
  12146. {
  12147. //
  12148. }
  12149. else if (methodInstance->mDeclModule != this)
  12150. {
  12151. // Is from specialized module?
  12152. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  12153. }
  12154. }
  12155. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12156. {
  12157. methodInstance->mIRFunction = BfIRFunction();
  12158. if (!mIsModuleMutable)
  12159. StartExtension();
  12160. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  12161. {
  12162. StringT<128> mangledName;
  12163. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  12164. bool isIntrinsic = false;
  12165. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  12166. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  12167. }
  12168. }
  12169. AddMethodToWorkList(methodInstance);
  12170. }
  12171. }
  12172. }
  12173. }
  12174. else
  12175. {
  12176. if (methodInstGroup->mDefault == NULL)
  12177. {
  12178. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12179. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12180. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12181. }
  12182. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  12183. if (methodInstGroup->mMethodSpecializationMap == NULL)
  12184. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  12185. BfMethodInstance** methodInstancePtr = NULL;
  12186. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  12187. {
  12188. methodInstance = *methodInstancePtr;
  12189. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  12190. return methodInstance;
  12191. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  12192. {
  12193. BfLogSysM("Setting mRequestedByAutocomplete=false for method instance %p\n", methodInstance);
  12194. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  12195. if (methodInstance->mMethodProcessRequest == NULL)
  12196. AddMethodToWorkList(methodInstance);
  12197. methodInstance->mRequestedByAutocomplete = false;
  12198. }
  12199. if ((isReified) && (!methodInstance->mIsReified))
  12200. {
  12201. MarkDerivedDirty(typeInst);
  12202. if (methodInstance->mHasBeenProcessed)
  12203. {
  12204. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  12205. delete methodInstance;
  12206. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12207. methodInstance = NULL;
  12208. }
  12209. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12210. {
  12211. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  12212. delete methodInstance;
  12213. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12214. methodInstance = NULL;
  12215. }
  12216. else
  12217. {
  12218. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  12219. // We haven't processed it yet
  12220. _SetReified();
  12221. CheckHotMethod(methodInstance, "");
  12222. if (methodInstance->mMethodProcessRequest == NULL)
  12223. AddMethodToWorkList(methodInstance);
  12224. }
  12225. }
  12226. }
  12227. }
  12228. if ((methodInstance != NULL) && (!doingRedeclare))
  12229. {
  12230. SetMethodDependency(methodInstance);
  12231. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  12232. {
  12233. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  12234. BF_ASSERT(!methodInstance->mIsReified);*/
  12235. if (methodInstance->mIsReified != isReified)
  12236. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  12237. if ((!isReified) &&
  12238. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  12239. {
  12240. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  12241. methodInstance->mIRFunction = BfIRFunction();
  12242. }
  12243. methodInstance->mIsReified = isReified;
  12244. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  12245. {
  12246. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  12247. }
  12248. if (!methodInstance->mMethodDef->mIsAbstract)
  12249. {
  12250. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  12251. {
  12252. // Wait until unreified
  12253. }
  12254. else
  12255. AddMethodToWorkList(methodInstance);
  12256. }
  12257. else
  12258. {
  12259. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  12260. auto owningModule = methodInstance->GetOwner()->mModule;
  12261. if (!owningModule->mIsScratchModule)
  12262. {
  12263. owningModule->mOnDemandMethodCount--;
  12264. owningModule->VerifyOnDemandMethods();
  12265. }
  12266. }
  12267. }
  12268. if (mExtensionCount > 0)
  12269. {
  12270. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  12271. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  12272. {
  12273. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  12274. if (mAwaitingInitFinish)
  12275. FinishInit();
  12276. // We need to refer to a function that was defined in a prior module
  12277. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12278. if (methodInstance->mIsIntrinsic)
  12279. isInlined = false;
  12280. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  12281. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  12282. methodInstance->mDeclModule = this;
  12283. // Add this inlined def to ourselves
  12284. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12285. {
  12286. mIncompleteMethodCount++;
  12287. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12288. inlineMethodRequest->mType = typeInst;
  12289. inlineMethodRequest->mFromModule = this;
  12290. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  12291. inlineMethodRequest->mFromModuleRevision = mRevision;
  12292. inlineMethodRequest->mMethodInstance = methodInstance;
  12293. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12294. BF_ASSERT(mIsModuleMutable);
  12295. }
  12296. }
  12297. }
  12298. if (IsSkippingExtraResolveChecks())
  12299. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12300. else
  12301. {
  12302. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12303. return methodInstance;
  12304. if (methodInstance->mDeclModule != this)
  12305. return ReferenceExternalMethodInstance(methodInstance, flags);
  12306. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  12307. {
  12308. auto importKind = methodInstance->GetImportCallKind();
  12309. if (importKind != BfImportCallKind_None)
  12310. {
  12311. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  12312. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  12313. auto func = CreateDllImportGlobalVar(methodInstance, true);
  12314. BF_ASSERT(func);
  12315. mFuncReferences[methodInstance] = func;
  12316. }
  12317. }
  12318. return BfModuleMethodInstance(methodInstance);
  12319. }
  12320. }
  12321. if (!doingRedeclare)
  12322. {
  12323. BfModule* specModule = NULL;
  12324. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  12325. {
  12326. specModule = GetSpecializedMethodModule(projectList);
  12327. }
  12328. if ((specModule != NULL) && (specModule != this))
  12329. {
  12330. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  12331. if (mAwaitingInitFinish)
  12332. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  12333. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12334. return specMethodInstance.mMethodInstance;
  12335. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  12336. }
  12337. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  12338. {
  12339. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  12340. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  12341. }
  12342. }
  12343. if (methodInstance == NULL)
  12344. {
  12345. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12346. {
  12347. BfLogSysM("GetMethodInstance (methodInstance == NULL) bailing due to IsCePaused\n");
  12348. return BfModuleMethodInstance();
  12349. }
  12350. if (lookupMethodGenericArguments.size() == 0)
  12351. {
  12352. BF_ASSERT(methodInstGroup->mDefault == NULL);
  12353. methodInstance = new BfMethodInstance();
  12354. methodInstGroup->mDefault = methodInstance;
  12355. BF_ASSERT(typeInst->mDefineState > BfTypeDefineState_Declared);
  12356. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  12357. }
  12358. else
  12359. {
  12360. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  12361. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12362. depthExceeded = true;
  12363. if (depthExceeded)
  12364. {
  12365. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  12366. return BfModuleMethodInstance();
  12367. }
  12368. BfMethodInstance** methodInstancePtr = NULL;
  12369. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  12370. BF_ASSERT(added);
  12371. methodInstance = new BfMethodInstance();
  12372. *methodInstancePtr = methodInstance;
  12373. if (mCompiler->IsAutocomplete())
  12374. methodInstance->mRequestedByAutocomplete = true;
  12375. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  12376. }
  12377. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  12378. methodInstance->mIRFunction = prevIRFunc; // Take it over
  12379. }
  12380. methodInstance->mMethodDef = methodDef;
  12381. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  12382. methodInstance->mMethodInstanceGroup = methodInstGroup;
  12383. methodInstance->mIsReified = isReified;
  12384. SetupMethodIdHash(methodInstance);
  12385. if (hadConcreteInterfaceGenericArgument)
  12386. methodInstance->mIgnoreBody = true;
  12387. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12388. {
  12389. methodInstance->mIsForeignMethodDef = true;
  12390. BF_ASSERT(foreignType != NULL);
  12391. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  12392. }
  12393. if ((typeInst->IsInstanceOf(mCompiler->mValueTypeTypeDef)) && (methodDef->mName == BF_METHODNAME_EQUALS))
  12394. {
  12395. if (!lookupMethodGenericArguments.empty())
  12396. {
  12397. auto compareType = lookupMethodGenericArguments[0];
  12398. PopulateType(compareType, BfPopulateType_Data);
  12399. if (compareType->IsSplattable())
  12400. methodInstance->mAlwaysInline = true;
  12401. }
  12402. }
  12403. if (methodDef->mMethodType == BfMethodType_Init)
  12404. {
  12405. methodInstance->mMangleWithIdx = true;
  12406. }
  12407. BF_ASSERT(typeInst == methodInstance->GetOwner());
  12408. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12409. if (isUnspecializedPass)
  12410. {
  12411. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  12412. {
  12413. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  12414. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  12415. }
  12416. }
  12417. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  12418. {
  12419. if (!sanitizedMethodGenericArguments.IsEmpty())
  12420. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  12421. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  12422. {
  12423. Fail("Internal error");
  12424. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  12425. return NULL;
  12426. }
  12427. for (auto genericArg : sanitizedMethodGenericArguments)
  12428. {
  12429. if (genericArg->IsPrimitiveType())
  12430. genericArg = GetWrappedStructType(genericArg);
  12431. if (genericArg != NULL)
  12432. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  12433. }
  12434. }
  12435. // Generic constraints
  12436. if (!methodDef->mGenericParams.IsEmpty())
  12437. {
  12438. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  12439. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  12440. {
  12441. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  12442. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12443. }
  12444. }
  12445. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  12446. {
  12447. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  12448. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12449. }
  12450. bool addToWorkList = !processNow;
  12451. if (mCompiler->GetAutoComplete() != NULL)
  12452. {
  12453. if (typeInst->IsSpecializedByAutoCompleteMethod())
  12454. addToWorkList = false;
  12455. if (methodInstance->mRequestedByAutocomplete)
  12456. addToWorkList = false;
  12457. }
  12458. BfModule* declareModule;
  12459. //
  12460. {
  12461. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  12462. declareModule = GetOrCreateMethodModule(methodInstance);
  12463. }
  12464. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  12465. declareModule = methodInstance->mDeclModule;
  12466. BF_ASSERT(declareModule != NULL);
  12467. methodInstance->mDeclModule = declareModule;
  12468. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  12469. {
  12470. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  12471. // of a reified module -
  12472. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  12473. // BUT if we don't reify it then we have to remove the body after processing.
  12474. // 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
  12475. // the proper reified module.
  12476. declareModule = mContext->mUnreifiedModule;
  12477. }
  12478. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  12479. {
  12480. if (!methodInstance->mIsReified)
  12481. {
  12482. declareModule = mContext->mUnreifiedModule;
  12483. }
  12484. else
  12485. {
  12486. declareModule->PrepareForIRWriting(methodInstance->GetOwner());
  12487. }
  12488. }
  12489. SetMethodDependency(methodInstance);
  12490. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  12491. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  12492. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  12493. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  12494. {
  12495. // For mixins we only process the unspecialized version
  12496. addToWorkList = false;
  12497. }
  12498. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  12499. {
  12500. addToWorkList = false;
  12501. }
  12502. // if ((flags & BfGetMethodInstanceFlag_NoReference) != 0)
  12503. // addToWorkList = false;
  12504. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  12505. if (processNow)
  12506. {
  12507. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  12508. ProcessMethod(methodInstance);
  12509. }
  12510. if (IsSkippingExtraResolveChecks())
  12511. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12512. if (methodInstance->mDeclModule != this)
  12513. return ReferenceExternalMethodInstance(methodInstance, flags);
  12514. return BfModuleMethodInstance(methodInstance);
  12515. }
  12516. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  12517. {
  12518. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  12519. if (methodInstance->mIsForeignMethodDef)
  12520. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  12521. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  12522. }
  12523. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  12524. {
  12525. if (!methodInstance->mMethodDef->mIsLocalMethod)
  12526. return NULL;
  12527. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  12528. if (outerLocal == NULL)
  12529. return NULL;
  12530. BfTypeVector genericArgs;
  12531. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  12532. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  12533. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  12534. }
  12535. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  12536. {
  12537. HashContext hashCtx;
  12538. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  12539. {
  12540. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  12541. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  12542. if (methodInstance->GetNumGenericArguments() != 0)
  12543. {
  12544. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  12545. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  12546. hashCtx.Mixin(methodGenericArg->mTypeId);
  12547. }
  12548. };
  12549. _MixinMethodInstance(methodInstance);
  12550. if (methodInstance->mMethodDef->mIsLocalMethod)
  12551. {
  12552. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  12553. if (outmostMethodInstance != NULL)
  12554. {
  12555. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  12556. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  12557. }
  12558. }
  12559. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  12560. }
  12561. bool BfModule::CheckUseMethodInstance(BfMethodInstance* methodInstance, BfAstNode* refNode)
  12562. {
  12563. if (methodInstance->mHasBeenDeclared)
  12564. return true;
  12565. Fail(StrFormat("Circular reference in method instance '%s'", MethodToString(methodInstance).c_str()), refNode);
  12566. return false;
  12567. }
  12568. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  12569. {
  12570. BfIRValue globalValue;
  12571. BfIRValue* globalValuePtr = NULL;
  12572. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  12573. {
  12574. globalValue = *globalValuePtr;
  12575. }
  12576. if (!globalValue)
  12577. {
  12578. // This is necessary to reify the interface type
  12579. PopulateType(ifaceType);
  12580. StringT<128> slotVarName;
  12581. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  12582. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  12583. BfIRValue value;
  12584. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  12585. {
  12586. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  12587. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  12588. int virtSlotIdx = ifaceType->mSlotNum + 1;
  12589. value = GetConstValue32(virtSlotIdx);*/
  12590. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  12591. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  12592. }
  12593. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  12594. mInterfaceSlotRefs[ifaceType] = globalValue;
  12595. }
  12596. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  12597. }
  12598. void BfModule::HadSlotCountDependency()
  12599. {
  12600. if (mCompiler->mIsResolveOnly)
  12601. return;
  12602. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  12603. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  12604. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  12605. }
  12606. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  12607. {
  12608. if (str == "#IsComptime")
  12609. {
  12610. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsComptimeModule ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  12611. }
  12612. if (str == "#IsBuilding")
  12613. {
  12614. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (!mCompiler->mIsResolveOnly) ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  12615. }
  12616. if (str == "#IsReified")
  12617. {
  12618. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsReified ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  12619. }
  12620. if (str == "#CompileRev")
  12621. {
  12622. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mRevision), GetPrimitiveType(BfTypeCode_Int32));
  12623. }
  12624. if (str == "#ModuleName")
  12625. {
  12626. return BfTypedValue(GetStringObjectValue(mModuleName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12627. }
  12628. if (str == "#ProjectName")
  12629. {
  12630. if (mProject != NULL)
  12631. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12632. }
  12633. if (str == "#AllocStackCount")
  12634. {
  12635. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mOptions.mAllocStackCount), GetPrimitiveType(BfTypeCode_Int32));
  12636. }
  12637. if (mCurMethodState->mMixinState != NULL)
  12638. {
  12639. if (str == "#CallerLineNum")
  12640. {
  12641. return BfTypedValue(GetConstValue(mCurMethodState->mMixinState->mInjectFilePosition.mCurLine + 1), GetPrimitiveType(BfTypeCode_Int32));
  12642. }
  12643. else if (str == "#CallerFilePath")
  12644. {
  12645. String filePath = "";
  12646. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  12647. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  12648. return BfTypedValue(GetStringObjectValue(filePath), ResolveTypeDef(mCompiler->mStringTypeDef));
  12649. }
  12650. else if (str == "#CallerFileName")
  12651. {
  12652. String filePath = "";
  12653. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  12654. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  12655. return BfTypedValue(GetStringObjectValue(GetFileName(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  12656. }
  12657. else if (str == "#CallerFileDir")
  12658. {
  12659. String filePath = "";
  12660. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  12661. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  12662. return BfTypedValue(GetStringObjectValue(GetFileDir(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  12663. }
  12664. else if (str == "#CallerMemberName")
  12665. {
  12666. String memberName = "";
  12667. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  12668. memberName = MethodToString(mCurMethodState->mMixinState->mMixinMethodInstance);
  12669. return BfTypedValue(GetStringObjectValue(memberName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12670. }
  12671. else if (str == "#CallerProject")
  12672. {
  12673. BfProject* project = NULL;
  12674. project = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mProject;
  12675. if (project != NULL)
  12676. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12677. }
  12678. }
  12679. if (str == "#TimeLocal")
  12680. {
  12681. time_t rawtime;
  12682. time(&rawtime);
  12683. tm* timeinfo = localtime(&rawtime);
  12684. char result[32];
  12685. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  12686. 1900 + timeinfo->tm_year,
  12687. timeinfo->tm_mon,
  12688. timeinfo->tm_mday,
  12689. timeinfo->tm_hour,
  12690. timeinfo->tm_min,
  12691. timeinfo->tm_sec);
  12692. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  12693. }
  12694. return BfTypedValue();
  12695. }
  12696. BfTypedValue BfModule::GetCompilerFieldValue(BfTypedValue typedValue)
  12697. {
  12698. if (!typedValue.IsAddr())
  12699. return BfTypedValue();
  12700. if (typedValue.mValue.IsConst())
  12701. {
  12702. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  12703. if (constantValue != NULL)
  12704. {
  12705. if (constantValue->mConstType == BfConstType_GlobalVar)
  12706. {
  12707. auto globalVar = (BfGlobalVar*)constantValue;
  12708. if (globalVar->mName[0] == '#')
  12709. {
  12710. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  12711. return result;
  12712. }
  12713. }
  12714. }
  12715. }
  12716. return BfTypedValue();
  12717. }
  12718. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  12719. {
  12720. BfIRValue globalValue;
  12721. auto fieldDef = fieldInstance->GetFieldDef();
  12722. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  12723. {
  12724. if (fieldInstance->mConstIdx != -1)
  12725. {
  12726. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  12727. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  12728. }
  12729. else
  12730. {
  12731. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  12732. }
  12733. }
  12734. if ((mIsScratchModule) && (mCompiler->mIsResolveOnly))
  12735. {
  12736. // Just fake it for the extern and unspecialized modules
  12737. // We can't do this for compilation because unreified methods with default params need to get acutal global variable refs
  12738. return BfTypedValue(mBfIRBuilder->CreateConstNull(), fieldInstance->GetResolvedType(), true);
  12739. }
  12740. BfIRValue* globalValuePtr = NULL;
  12741. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  12742. {
  12743. globalValue = *globalValuePtr;
  12744. BF_ASSERT(globalValue);
  12745. auto globalVar = (BfGlobalVar*)mBfIRBuilder->GetConstant(globalValue);
  12746. if ((globalVar->mStreamId == -1) && (!mBfIRBuilder->mIgnoreWrites))
  12747. {
  12748. mBfIRBuilder->MapType(fieldInstance->mResolvedType);
  12749. mBfIRBuilder->CreateGlobalVariable(globalValue);
  12750. }
  12751. }
  12752. else
  12753. {
  12754. StringT<128> staticVarName;
  12755. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  12756. auto typeType = fieldInstance->GetResolvedType();
  12757. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  12758. {
  12759. typeType = typeType->GetUnderlyingType();
  12760. }
  12761. if (mIsComptimeModule)
  12762. {
  12763. mCompiler->mCeMachine->QueueStaticField(fieldInstance, staticVarName);
  12764. }
  12765. PopulateType(typeType);
  12766. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  12767. {
  12768. BfIRType irType = mBfIRBuilder->MapType(typeType);
  12769. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  12770. globalValue = mBfIRBuilder->CreateGlobalVariable(
  12771. irType,
  12772. false,
  12773. BfIRLinkageType_External,
  12774. BfIRValue(),
  12775. staticVarName,
  12776. IsThreadLocal(fieldInstance));
  12777. BF_ASSERT(globalValue);
  12778. mStaticFieldRefs[fieldInstance] = globalValue;
  12779. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  12780. }
  12781. }
  12782. auto type = fieldInstance->GetResolvedType();
  12783. if (type->IsValuelessType())
  12784. return BfTypedValue(globalValue, type);
  12785. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  12786. }
  12787. int BfModule::GetFieldDataIdx(BfTypeInstance* typeInst, int fieldIdx, const char* fieldName)
  12788. {
  12789. if (typeInst->IsDataIncomplete())
  12790. PopulateType(typeInst);
  12791. if (fieldIdx >= typeInst->mFieldInstances.mSize)
  12792. {
  12793. Fail(StrFormat("Invalid field data in type '%s'", TypeToString(typeInst).c_str()));
  12794. return 0;
  12795. }
  12796. auto& fieldInstance = typeInst->mFieldInstances[fieldIdx];
  12797. return fieldInstance.mDataIdx;
  12798. }
  12799. void BfModule::MarkUsingThis()
  12800. {
  12801. auto useMethodState = mCurMethodState;
  12802. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  12803. {
  12804. useMethodState = useMethodState->mPrevMethodState;
  12805. }
  12806. if ((useMethodState != NULL) && (!useMethodState->mLocals.IsEmpty()))
  12807. {
  12808. auto localVar = useMethodState->mLocals[0];
  12809. if (localVar->mIsThis)
  12810. localVar->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  12811. }
  12812. }
  12813. BfTypedValue BfModule::GetThis(bool markUsing)
  12814. {
  12815. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  12816. {
  12817. if (mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis)
  12818. return mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis;
  12819. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  12820. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  12821. if ((activeFrame != NULL) && (activeFrame->mFunction->mDbgInfo != NULL))
  12822. {
  12823. for (auto& dbgVar : activeFrame->mFunction->mDbgInfo->mVariables)
  12824. {
  12825. if (dbgVar.mName == "this")
  12826. return BfTypedValue(mBfIRBuilder->CreateConstAggCE(mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs), dbgVar.mType,
  12827. dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  12828. }
  12829. }
  12830. return BfTypedValue();
  12831. }
  12832. auto useMethodState = mCurMethodState;
  12833. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  12834. {
  12835. useMethodState = useMethodState->mPrevMethodState;
  12836. }
  12837. if (useMethodState != NULL)
  12838. {
  12839. // Fake a 'this' for var field resolution
  12840. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  12841. {
  12842. auto thisType = mCurTypeInstance;
  12843. if (thisType->IsValueType())
  12844. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  12845. else
  12846. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  12847. }
  12848. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  12849. {
  12850. return BfTypedValue();
  12851. }
  12852. }
  12853. else
  12854. {
  12855. //TODO: Do we allow useMethodState to be NULL anymore?
  12856. return BfTypedValue();
  12857. }
  12858. // Check mixin state for 'this'
  12859. {
  12860. auto checkMethodState = mCurMethodState;
  12861. while (checkMethodState != NULL)
  12862. {
  12863. if (checkMethodState->mMixinState != NULL)
  12864. {
  12865. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  12866. if (thisValue.HasType())
  12867. {
  12868. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  12869. if (!thisValue.mType->IsValueType())
  12870. thisValue = LoadValue(thisValue);
  12871. return thisValue;
  12872. }
  12873. }
  12874. checkMethodState = checkMethodState->mPrevMethodState;
  12875. }
  12876. }
  12877. auto curMethodInstance = mCurMethodInstance;
  12878. if (useMethodState->mMethodInstance != NULL)
  12879. curMethodInstance = useMethodState->mMethodInstance;
  12880. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  12881. {
  12882. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  12883. {
  12884. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  12885. if (constLocal.mIsThis)
  12886. {
  12887. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  12888. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  12889. }
  12890. }
  12891. return BfTypedValue();
  12892. }
  12893. if (useMethodState->mLocals.IsEmpty())
  12894. {
  12895. // 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
  12896. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  12897. return BfTypedValue();
  12898. }
  12899. auto thisLocal = useMethodState->mLocals[0];
  12900. BF_ASSERT(thisLocal->mIsThis);
  12901. bool preferValue = !IsTargetingBeefBackend();
  12902. if (!thisLocal->mAddr)
  12903. preferValue = true;
  12904. bool usedVal = false;
  12905. BfIRValue thisValue;
  12906. if ((preferValue) && (!thisLocal->mIsLowered))
  12907. {
  12908. thisValue = thisLocal->mValue;
  12909. usedVal = true;
  12910. }
  12911. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  12912. thisValue = thisLocal->mAddr;
  12913. else
  12914. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  12915. if (markUsing)
  12916. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  12917. if (useMethodState->mClosureState != NULL)
  12918. {
  12919. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  12920. if (closureTypeInst != NULL)
  12921. {
  12922. if (closureTypeInst->mFieldInstances.size() > 0)
  12923. {
  12924. auto& field = closureTypeInst->mFieldInstances[0];
  12925. auto fieldDef = field.GetFieldDef();
  12926. if (fieldDef->mName == "__this")
  12927. {
  12928. if (mCurMethodState->mClosureState->mCapturing)
  12929. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  12930. // This is a captured 'this'
  12931. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  12932. if (field.mResolvedType->IsRef())
  12933. {
  12934. auto refType = (BfRefType*)field.mResolvedType;
  12935. auto underlyingType = refType->GetUnderlyingType();
  12936. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  12937. }
  12938. if (field.mResolvedType->IsObject())
  12939. {
  12940. result = LoadValue(result);
  12941. result.mKind = BfTypedValueKind_ThisValue;
  12942. }
  12943. else
  12944. {
  12945. if (fieldDef->mIsReadOnly)
  12946. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  12947. else
  12948. result.mKind = BfTypedValueKind_ThisAddr;
  12949. }
  12950. return result;
  12951. }
  12952. }
  12953. return BfTypedValue();
  12954. }
  12955. if (useMethodState->mClosureState->mCapturing)
  12956. {
  12957. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  12958. if (thisType->IsValueType())
  12959. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  12960. else
  12961. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  12962. }
  12963. }
  12964. if (mCurMethodInstance == NULL)
  12965. return BfTypedValue();
  12966. auto localDef = useMethodState->mLocals[0];
  12967. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  12968. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  12969. {
  12970. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  12971. {
  12972. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  12973. }
  12974. if (localDef->mIsSplat)
  12975. {
  12976. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  12977. }
  12978. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  12979. }
  12980. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  12981. }
  12982. BfLocalVariable* BfModule::GetThisVariable()
  12983. {
  12984. if (mCurMethodState == NULL)
  12985. return NULL;
  12986. auto methodState = mCurMethodState->GetNonCaptureState();
  12987. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  12988. return methodState->mLocals[0];
  12989. return NULL;
  12990. }
  12991. bool BfModule::IsInGeneric()
  12992. {
  12993. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  12994. }
  12995. bool BfModule::InDefinitionSection()
  12996. {
  12997. if (mCurTypeInstance != NULL)
  12998. {
  12999. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  13000. return false;
  13001. }
  13002. return !IsInSpecializedSection();
  13003. }
  13004. bool BfModule::IsInSpecializedGeneric()
  13005. {
  13006. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  13007. return true;
  13008. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  13009. return false;
  13010. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  13011. }
  13012. bool BfModule::IsInSpecializedSection()
  13013. {
  13014. return IsInSpecializedGeneric() ||
  13015. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  13016. }
  13017. bool BfModule::IsInUnspecializedGeneric()
  13018. {
  13019. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  13020. return true;
  13021. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedType()))
  13022. return true;
  13023. return false;
  13024. }
  13025. //////////////////////////////////////////////////////////////////////////
  13026. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  13027. {
  13028. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  13029. if (type->IsValuelessType())
  13030. return mBfIRBuilder->GetFakeVal();
  13031. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  13032. if ((!doLifetimeEnd) && (WantsLifetimes()))
  13033. {
  13034. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  13035. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  13036. }
  13037. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  13038. auto typeOptions = GetTypeOptions();
  13039. if (typeOptions != NULL)
  13040. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  13041. // Local variable inits are implicitly handled in the Beef Backend
  13042. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  13043. {
  13044. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13045. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13046. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  13047. mBfIRBuilder->ClearDebugLocation(storeInst);
  13048. mBfIRBuilder->SetInsertPoint(prevBlock);
  13049. }
  13050. return allocaInst;
  13051. }
  13052. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  13053. {
  13054. while (localVar->mName.StartsWith('@'))
  13055. {
  13056. localVar->mNamePrefixCount++;
  13057. localVar->mName.Remove(0);
  13058. }
  13059. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  13060. mCurMethodState->mLocals.push_back(localVar);
  13061. BfLocalVarEntry* localVarEntryPtr;
  13062. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  13063. {
  13064. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  13065. localVarEntryPtr->mLocalVar = localVar;
  13066. }
  13067. }
  13068. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13069. {
  13070. if (localVarDef->mResolvedType->IsVar())
  13071. return;
  13072. if ((mBfIRBuilder->DbgHasInfo()) &&
  13073. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  13074. (mHasFullDebugInfo) &&
  13075. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  13076. {
  13077. auto varType = localVarDef->mResolvedType;
  13078. if (localVarDef->mResolvedType->IsValuelessType())
  13079. {
  13080. }
  13081. else
  13082. {
  13083. bool isByAddr = false;
  13084. auto diValue = localVarDef->mValue;
  13085. if (localVarDef->mConstValue)
  13086. diValue = localVarDef->mConstValue;
  13087. else if (localVarDef->mAddr)
  13088. {
  13089. diValue = localVarDef->mAddr;
  13090. isByAddr = true;
  13091. }
  13092. if (diValue.IsConst())
  13093. {
  13094. auto constant = mBfIRBuilder->GetConstant(diValue);
  13095. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  13096. {
  13097. // Ignore for now
  13098. return;
  13099. }
  13100. }
  13101. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  13102. bool didConstToMem = false;
  13103. bool isConstant = false;
  13104. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  13105. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13106. else if (localVarDef->mConstValue)
  13107. {
  13108. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  13109. isConstant =
  13110. (constant->mConstType < BfConstType_GlobalVar) ||
  13111. (constant->mConstType == BfConstType_AggZero) ||
  13112. (constant->mConstType == BfConstType_Agg);
  13113. if (isConstant)
  13114. {
  13115. if (localVarDef->mResolvedType->IsComposite())
  13116. {
  13117. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  13118. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  13119. // if (IsTargetingBeefBackend())
  13120. // {
  13121. // diValue = mBfIRBuilder->CreateAliasValue(constMem);
  13122. // didConstToMem = true;
  13123. //
  13124. // diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13125. // }
  13126. //else
  13127. {
  13128. isByAddr = true;
  13129. mBfIRBuilder->SaveDebugLocation();
  13130. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13131. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13132. mBfIRBuilder->ClearDebugLocation();
  13133. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  13134. auto addrVal = CreateAlloca(ptrType);
  13135. mBfIRBuilder->CreateStore(constMem, addrVal);
  13136. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13137. diValue = addrVal;
  13138. didConstToMem = true;
  13139. mBfIRBuilder->SetInsertPoint(prevBlock);
  13140. mBfIRBuilder->RestoreDebugLocation();
  13141. }
  13142. }
  13143. if (mCompiler->mOptions.IsCodeView())
  13144. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13145. }
  13146. }
  13147. if (!mBfIRBuilder->mIgnoreWrites)
  13148. {
  13149. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13150. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  13151. localVarDef->mDbgVarInst = diVariable;
  13152. if (mBfIRBuilder->HasDebugLocation())
  13153. {
  13154. if ((isConstant) && (!didConstToMem))
  13155. {
  13156. BfTypedValue result(localVarDef->mConstValue, localVarDef->mResolvedType);
  13157. FixValueActualization(result);
  13158. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(result.mValue, diVariable);
  13159. }
  13160. else
  13161. {
  13162. if ((IsTargetingBeefBackend()) && (doAliasValue) && (!mIsComptimeModule))
  13163. {
  13164. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  13165. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  13166. }
  13167. if (isByAddr)
  13168. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  13169. else if (diValue)
  13170. {
  13171. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  13172. }
  13173. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  13174. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  13175. }
  13176. }
  13177. }
  13178. }
  13179. }
  13180. }
  13181. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13182. {
  13183. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  13184. {
  13185. if ((!localVarDef->mValue.IsConst()) &&
  13186. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  13187. {
  13188. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  13189. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  13190. }
  13191. }
  13192. if (addDebugInfo)
  13193. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  13194. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  13195. DoAddLocalVariable(localVarDef);
  13196. auto rootMethodState = mCurMethodState->GetRootMethodState();
  13197. if (localVarDef->mLocalVarId == -1)
  13198. {
  13199. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  13200. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  13201. }
  13202. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!mIsComptimeModule))
  13203. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  13204. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  13205. {
  13206. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  13207. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL) && (rootMethodState->mMethodInstance != NULL) && (!mIsComptimeModule))
  13208. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  13209. }
  13210. return localVarDef;
  13211. }
  13212. void BfModule::CreateDIRetVal()
  13213. {
  13214. if (!WantsDebugInfo())
  13215. return;
  13216. /*if (!mCurMethodState->mRetVal)
  13217. {
  13218. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  13219. return;
  13220. }*/
  13221. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  13222. {
  13223. BfType* dbgType = mCurMethodInstance->mReturnType;
  13224. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  13225. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13226. {
  13227. BF_ASSERT(mCurMethodState->mRetValAddr);
  13228. dbgType = CreatePointerType(dbgType);
  13229. dbgValue = mCurMethodState->mRetValAddr;
  13230. }
  13231. else
  13232. {
  13233. BF_ASSERT(!mCurMethodState->mRetValAddr);
  13234. }
  13235. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13236. "@return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  13237. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  13238. }
  13239. }
  13240. BfTypedValue BfModule::CreateTuple(const Array<BfTypedValue>& values, const Array<String>& fieldNames)
  13241. {
  13242. BfTypeVector fieldTypes;
  13243. for (auto arg : values)
  13244. fieldTypes.Add(arg.mType);
  13245. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  13246. auto tupleTypedValue = BfTypedValue(CreateAlloca(tupleType), tupleType, true);
  13247. for (int fieldIdx = 0; fieldIdx < tupleType->mFieldInstances.size(); fieldIdx++)
  13248. {
  13249. auto& fieldInstance = tupleType->mFieldInstances[fieldIdx];
  13250. if (fieldInstance.mDataIdx <= 0)
  13251. continue;
  13252. auto typedVal = values[fieldIdx];
  13253. typedVal = LoadOrAggregateValue(typedVal);
  13254. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, mBfIRBuilder->CreateInBoundsGEP(tupleTypedValue.mValue, 0, fieldInstance.mDataIdx), typedVal.mType->mAlign);
  13255. }
  13256. return tupleTypedValue;
  13257. }
  13258. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  13259. {
  13260. if (variableDef->mName.IsEmpty())
  13261. return;
  13262. BfLocalVarEntry* localVarEntryPtr = NULL;
  13263. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  13264. {
  13265. auto checkLocal = localVarEntryPtr->mLocalVar;
  13266. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  13267. {
  13268. BfError* error;
  13269. if (checkLocal->mIsImplicitParam)
  13270. return; // Ignore 'redefinition'
  13271. if (checkLocal->IsParam())
  13272. {
  13273. if (variableDef->IsParam())
  13274. error = Fail(StrFormat("A parameter named '%s' has already been declared", variableDef->mName.c_str()), variableDef->mNameNode);
  13275. else
  13276. 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);
  13277. }
  13278. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  13279. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13280. else
  13281. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13282. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  13283. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  13284. return;
  13285. }
  13286. }
  13287. }
  13288. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  13289. {
  13290. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  13291. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  13292. {
  13293. if (tokenNode->GetToken() == BfToken_Colon)
  13294. {
  13295. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  13296. {
  13297. Fail("Cannot access method scope across deferred block boundary", scopeName);
  13298. return NULL;
  13299. }
  13300. return &mCurMethodState->mHeadScope;
  13301. }
  13302. else if (tokenNode->GetToken() == BfToken_Mixin)
  13303. {
  13304. if (fromMixinState == NULL)
  13305. {
  13306. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  13307. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  13308. return mCurMethodState->mCurScope;
  13309. }
  13310. fromMixinState->mUsedInvocationScope = true;
  13311. return fromMixinState->mTargetScope;
  13312. }
  13313. else if (tokenNode->GetToken() == BfToken_New)
  13314. return NULL;
  13315. }
  13316. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  13317. {
  13318. auto findLabel = scopeName->ToString();
  13319. bool crossedDeferredBlock = false;
  13320. auto checkScope = mCurMethodState->mCurScope;
  13321. while (checkScope != NULL)
  13322. {
  13323. if (checkScope->mIsDeferredBlock)
  13324. crossedDeferredBlock = true;
  13325. if (checkScope->mLabel == findLabel)
  13326. {
  13327. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  13328. {
  13329. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  13330. return NULL;
  13331. }
  13332. return checkScope;
  13333. }
  13334. checkScope = checkScope->mPrevScope;
  13335. }
  13336. if (!inMixinDecl)
  13337. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  13338. }
  13339. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  13340. {
  13341. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  13342. }
  13343. return mCurMethodState->mCurScope;
  13344. }
  13345. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  13346. {
  13347. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  13348. }
  13349. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  13350. {
  13351. auto scopeData = FindScope(scopeName, false);
  13352. if (scopeData == NULL)
  13353. return NULL;
  13354. int scopeDepth = scopeData->GetDepth();
  13355. // Find the first break data that is at or below the depth of our requested scope
  13356. auto breakData = mCurMethodState->mBreakData;
  13357. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  13358. {
  13359. if (breakData->mScope->mIsConditional)
  13360. return NULL;
  13361. breakData = breakData->mPrevBreakData;
  13362. }
  13363. return breakData;
  13364. }
  13365. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  13366. {
  13367. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  13368. if (!IsTargetingBeefBackend())
  13369. return;
  13370. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  13371. {
  13372. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13373. }
  13374. }
  13375. void BfModule::ClearLifetimeEnds()
  13376. {
  13377. auto scopeData = mCurMethodState->mCurScope;
  13378. while (scopeData != NULL)
  13379. {
  13380. scopeData->mDeferredLifetimeEnds.Clear();
  13381. scopeData = scopeData->mPrevScope;
  13382. }
  13383. }
  13384. bool BfModule::WantsDebugInfo()
  13385. {
  13386. if ((mCurMethodInstance != NULL) &&
  13387. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  13388. return false;
  13389. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  13390. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  13391. }
  13392. BfTypeOptions* BfModule::GetTypeOptions()
  13393. {
  13394. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  13395. return mCurMethodState->mMethodTypeOptions;
  13396. if (mCurMethodInstance == NULL)
  13397. return NULL;
  13398. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  13399. }
  13400. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  13401. {
  13402. BfReflectKind reflectKind = BfReflectKind_None;
  13403. if (attrType->mCustomAttributes != NULL)
  13404. {
  13405. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  13406. {
  13407. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  13408. {
  13409. for (auto& prop : customAttr.mSetProperties)
  13410. {
  13411. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  13412. if (propDef->mName == "ReflectUser")
  13413. {
  13414. if (prop.mParam.mValue.IsConst())
  13415. {
  13416. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  13417. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  13418. }
  13419. }
  13420. }
  13421. // Check for Flags arg
  13422. if (customAttr.mCtorArgs.size() < 2)
  13423. continue;
  13424. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  13425. if (constant == NULL)
  13426. continue;
  13427. if (constant->mTypeCode == BfTypeCode_Boolean)
  13428. continue;
  13429. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  13430. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  13431. }
  13432. }
  13433. }
  13434. return reflectKind;
  13435. }
  13436. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  13437. {
  13438. auto checkTypeInstance = typeInstance;
  13439. while (checkTypeInstance != NULL)
  13440. {
  13441. if (checkTypeInstance->mCustomAttributes != NULL)
  13442. {
  13443. auto checkReflectKind = BfReflectKind_None;
  13444. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  13445. {
  13446. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  13447. {
  13448. if (customAttr.mCtorArgs.size() > 0)
  13449. {
  13450. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  13451. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  13452. }
  13453. else
  13454. {
  13455. checkReflectKind = BfReflectKind_All;
  13456. }
  13457. }
  13458. else
  13459. {
  13460. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  13461. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  13462. }
  13463. }
  13464. if ((checkTypeInstance == typeInstance) ||
  13465. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  13466. {
  13467. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  13468. }
  13469. }
  13470. for (auto ifaceEntry : typeInstance->mInterfaces)
  13471. {
  13472. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  13473. {
  13474. auto iface = ifaceEntry.mInterfaceType;
  13475. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  13476. if (customAttr != NULL)
  13477. {
  13478. for (auto& prop : customAttr->mSetProperties)
  13479. {
  13480. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  13481. if (propDef->mName == "ReflectImplementer")
  13482. {
  13483. if (prop.mParam.mValue.IsConst())
  13484. {
  13485. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  13486. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  13487. }
  13488. }
  13489. }
  13490. }
  13491. }
  13492. }
  13493. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  13494. }
  13495. return reflectKind;
  13496. }
  13497. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  13498. {
  13499. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13500. while (checkScope != NULL)
  13501. {
  13502. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  13503. return true;
  13504. if (checkScope == scope)
  13505. break;
  13506. checkScope = checkScope->mPrevScope;
  13507. }
  13508. return false;
  13509. }
  13510. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  13511. {
  13512. // Is there anything we need to do here?
  13513. if (mBfIRBuilder->mIgnoreWrites)
  13514. {
  13515. // Just visit deferred blocks
  13516. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13517. while (checkScope != NULL)
  13518. {
  13519. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  13520. while (deferredCallEntry != NULL)
  13521. {
  13522. if (deferredCallEntry->mDeferredBlock != NULL)
  13523. {
  13524. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  13525. if (checkScope == &mCurMethodState->mHeadScope)
  13526. CreateRetValLocal();
  13527. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry->mEmitRefNode);
  13528. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  13529. }
  13530. deferredCallEntry = deferredCallEntry->mNext;
  13531. }
  13532. if (checkScope == scopeData)
  13533. break;
  13534. checkScope = checkScope->mPrevScope;
  13535. }
  13536. return;
  13537. }
  13538. // Why did we want to do SetIllegalSrcPos here?
  13539. // Don't we always want to step onto these instances?
  13540. // Find a case where we don't and perhaps only do it there.
  13541. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  13542. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  13543. //SetIllegalSrcPos();
  13544. bool setSrcPos = false;
  13545. bool wantsNop = true;
  13546. BfAstNode* deferCloseNode = NULL;
  13547. if (mCurMethodState->mInPostReturn)
  13548. {
  13549. // These won't get used, they are post-return
  13550. return;
  13551. }
  13552. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  13553. BfScopeData* scopeJumpBlock = NULL;
  13554. bool hadExtraDeferredLifetimeEnds = false;
  13555. auto _FlushLifetimeEnds = [&]()
  13556. {
  13557. for (auto lifetimeEnd : deferredLifetimeEnds)
  13558. {
  13559. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13560. mBfIRBuilder->ClearDebugLocation_Last();
  13561. }
  13562. deferredLifetimeEnds.clear();
  13563. };
  13564. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13565. while (checkScope != NULL)
  13566. {
  13567. if (checkScope->mCloseNode != NULL)
  13568. deferCloseNode = checkScope->mCloseNode;
  13569. if (doneBlock)
  13570. {
  13571. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  13572. for (auto& checkHandler : checkScope->mDeferredHandlers)
  13573. {
  13574. if (checkHandler.mDoneBlock == doneBlock)
  13575. {
  13576. scopeJumpBlock = checkScope;
  13577. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  13578. mBfIRBuilder->ClearDebugLocation_Last();
  13579. _FlushLifetimeEnds();
  13580. break;
  13581. }
  13582. }
  13583. if (scopeJumpBlock != NULL)
  13584. break;
  13585. }
  13586. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  13587. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  13588. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  13589. if (hasWork)
  13590. {
  13591. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  13592. if (deferCloseNode != NULL)
  13593. {
  13594. UpdateSrcPos(deferCloseNode);
  13595. }
  13596. if (checkScope == &mCurMethodState->mHeadScope)
  13597. CreateRetValLocal();
  13598. if (doneBlock)
  13599. {
  13600. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  13601. String blockName = "deferredCalls";
  13602. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  13603. BfDeferredHandler deferredHandler;
  13604. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  13605. {
  13606. mBfIRBuilder->SaveDebugLocation();
  13607. mBfIRBuilder->ClearDebugLocation();
  13608. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  13609. mBfIRBuilder->RestoreDebugLocation();
  13610. }
  13611. else
  13612. {
  13613. // Definitely chain
  13614. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  13615. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  13616. mBfIRBuilder->ClearDebugLocation_Last();
  13617. _FlushLifetimeEnds();
  13618. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  13619. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  13620. }
  13621. deferredHandler.mDoneBlock = doneBlock;
  13622. if (!mBfIRBuilder->mIgnoreWrites)
  13623. checkScope->mDeferredHandlers.push_back(deferredHandler);
  13624. if (checkScope == &mCurMethodState->mHeadScope)
  13625. {
  13626. if (!mCurMethodState->mDIRetVal)
  13627. {
  13628. // 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
  13629. // be scoped to the physical method
  13630. /*if (deferCloseNode != NULL)
  13631. {
  13632. UpdateSrcPos(deferCloseNode);
  13633. }*/
  13634. CreateDIRetVal();
  13635. }
  13636. }
  13637. if (checkScope != mCurMethodState->mTailScope)
  13638. {
  13639. if (deferredHandler.mHandlerBlock.IsFake())
  13640. {
  13641. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  13642. }
  13643. if (!mBfIRBuilder->mIgnoreWrites)
  13644. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  13645. }
  13646. }
  13647. std::unordered_set<BfDeferredCallEntry*> handledSet;
  13648. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  13649. while (deferredCallEntry != NULL)
  13650. {
  13651. BfDeferredCallEmitState deferredCallEmitState;
  13652. deferredCallEmitState.mCloseNode = deferCloseNode;
  13653. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  13654. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  13655. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  13656. if (deferCloseNode != NULL)
  13657. {
  13658. UpdateSrcPos(deferCloseNode);
  13659. }
  13660. if (wantsNop)
  13661. EmitEnsureInstructionAt();
  13662. wantsNop = false;
  13663. if (deferredCallEntry->mDeferredBlock != NULL)
  13664. {
  13665. auto itr = handledSet.insert(deferredCallEntry);
  13666. if (!itr.second)
  13667. {
  13668. // Already handled, can happen if we defer again within the block
  13669. deferredCallEntry = deferredCallEntry->mNext;
  13670. continue;
  13671. }
  13672. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  13673. EmitDeferredCall(*deferredCallEntry, true);
  13674. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  13675. {
  13676. // The list changed, start over and ignore anything we've already handled
  13677. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  13678. }
  13679. else
  13680. deferredCallEntry = deferredCallEntry->mNext;
  13681. }
  13682. else
  13683. {
  13684. EmitDeferredCall(*deferredCallEntry, true);
  13685. deferredCallEntry = deferredCallEntry->mNext;
  13686. }
  13687. }
  13688. if (checkScope->mSavedStack)
  13689. {
  13690. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  13691. if (mCurMethodState->mDynStackRevIdx)
  13692. {
  13693. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  13694. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  13695. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  13696. }
  13697. }
  13698. }
  13699. if (!checkScope->mIsScopeHead)
  13700. {
  13701. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  13702. if (!IsTargetingBeefBackend())
  13703. {
  13704. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  13705. {
  13706. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13707. }
  13708. }
  13709. else
  13710. {
  13711. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  13712. {
  13713. deferredLifetimeEnds.Add(lifetimeEnd);
  13714. }
  13715. }
  13716. }
  13717. if (checkScope == scopeData)
  13718. break;
  13719. checkScope = checkScope->mPrevScope;
  13720. }
  13721. if ((doneBlock) && (scopeJumpBlock == NULL))
  13722. {
  13723. mBfIRBuilder->CreateBr(doneBlock);
  13724. mBfIRBuilder->ClearDebugLocation_Last();
  13725. }
  13726. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  13727. // may have been created when other scope lifetimes were available
  13728. _FlushLifetimeEnds();
  13729. // Emit lifetimeEnds after the branch for Beef
  13730. /*if (IsTargetingBeefBackend())
  13731. {
  13732. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  13733. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13734. while (checkScope != NULL)
  13735. {
  13736. if (checkScope == scopeJumpBlock)
  13737. break;
  13738. if (!checkScope->mIsScopeHead)
  13739. {
  13740. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  13741. {
  13742. if (needsEnsureInst)
  13743. {
  13744. needsEnsureInst = false;
  13745. }
  13746. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13747. }
  13748. }
  13749. if (checkScope == scopeData)
  13750. break;
  13751. checkScope = checkScope->mPrevScope;
  13752. }
  13753. }*/
  13754. }
  13755. void BfModule::MarkScopeLeft(BfScopeData* scopeData, bool isNoReturn)
  13756. {
  13757. if ((mCurMethodState->mDeferredLocalAssignData != NULL) && (!isNoReturn))
  13758. {
  13759. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  13760. while (deferredLocalAssignData != NULL)
  13761. {
  13762. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  13763. break;
  13764. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  13765. deferredLocalAssignData->mIsUnconditional = false;
  13766. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  13767. }
  13768. }
  13769. // When we leave a scope, mark those as assigned for deferred assignment purposes
  13770. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  13771. {
  13772. auto localDef = mCurMethodState->mLocals[localIdx];
  13773. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  13774. {
  13775. bool hadAssignment = false;
  13776. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  13777. {
  13778. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  13779. if (entry.mLocalVar == localDef)
  13780. hadAssignment = true;
  13781. }
  13782. if (!hadAssignment)
  13783. {
  13784. if (!isNoReturn)
  13785. localDef->mHadExitBeforeAssign = true;
  13786. mCurMethodState->LocalDefined(localDef);
  13787. }
  13788. }
  13789. }
  13790. }
  13791. void BfModule::CreateReturn(BfIRValue val)
  13792. {
  13793. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13794. {
  13795. // Store to sret
  13796. BF_ASSERT(val);
  13797. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  13798. mBfIRBuilder->CreateRetVoid();
  13799. return;
  13800. }
  13801. if (mCurMethodInstance->mReturnType->IsVar())
  13802. return;
  13803. if (mCurMethodInstance->mReturnType->IsValuelessType())
  13804. {
  13805. mBfIRBuilder->CreateRetVoid();
  13806. return;
  13807. }
  13808. if (mCurMethodInstance->mReturnType->IsStruct())
  13809. {
  13810. BfTypeCode loweredReturnType = BfTypeCode_None;
  13811. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  13812. if (!mIsComptimeModule)
  13813. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  13814. if (loweredReturnType != BfTypeCode_None)
  13815. {
  13816. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  13817. mBfIRBuilder->CreateStore(val, retVal);
  13818. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  13819. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  13820. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  13821. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  13822. mBfIRBuilder->CreateRet(loadedReturnValue);
  13823. return;
  13824. }
  13825. }
  13826. BF_ASSERT(val);
  13827. mBfIRBuilder->CreateRet(val);
  13828. }
  13829. void BfModule::EmitReturn(const BfTypedValue& val)
  13830. {
  13831. if (mCurMethodState->mIRExitBlock)
  13832. {
  13833. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  13834. {
  13835. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  13836. {
  13837. if ((mCurMethodState->mRetValAddr) || (mCurMethodState->mRetVal))
  13838. {
  13839. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  13840. if (!mCurMethodState->mRetVal)
  13841. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  13842. mBfIRBuilder->CreateStore(val.mValue, retVal);
  13843. }
  13844. else if (mIsComptimeModule)
  13845. {
  13846. if (!val.mType->IsValuelessType())
  13847. mBfIRBuilder->CreateSetRet(val.mValue, val.mType->mTypeId);
  13848. else
  13849. mBfIRBuilder->CreateSetRet(BfIRValue(), val.mType->mTypeId);
  13850. }
  13851. else
  13852. {
  13853. // Just ignore
  13854. BF_ASSERT(mCurMethodInstance->mReturnType->IsVar());
  13855. }
  13856. }
  13857. }
  13858. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  13859. }
  13860. else
  13861. {
  13862. EmitDeferredScopeCalls(false, NULL);
  13863. if (val)
  13864. {
  13865. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  13866. }
  13867. }
  13868. mCurMethodState->SetHadReturn(true);
  13869. mCurMethodState->mLeftBlockUncond = true;
  13870. }
  13871. void BfModule::EmitDefaultReturn()
  13872. {
  13873. if (mCurMethodState->mInDeferredBlock)
  13874. return;
  13875. if (mCurMethodState->mIRExitBlock)
  13876. {
  13877. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  13878. }
  13879. else
  13880. {
  13881. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mReturnType->IsVar()))
  13882. {
  13883. // Ignore
  13884. }
  13885. else if (mCurMethodInstance->mReturnType->IsVoid())
  13886. mBfIRBuilder->CreateRetVoid();
  13887. else if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == -1))
  13888. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  13889. }
  13890. mCurMethodState->SetHadReturn(true);
  13891. mCurMethodState->mLeftBlockUncond = true;
  13892. }
  13893. void BfModule::AssertErrorState()
  13894. {
  13895. if (mIgnoreErrors)
  13896. return;
  13897. if (mHadBuildError)
  13898. return;
  13899. if (mCurTypeInstance != NULL)
  13900. {
  13901. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  13902. return;
  13903. }
  13904. if (mCurMethodInstance != NULL)
  13905. {
  13906. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  13907. return;
  13908. if (mCurMethodInstance->mHasFailed)
  13909. return;
  13910. }
  13911. // We want the module to be marked as failed even if it's just an error in the parser
  13912. if (mCurMethodInstance != NULL)
  13913. mCurMethodInstance->mHasFailed = true;
  13914. mHadBuildError = true;
  13915. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  13916. if (mCurTypeInstance != NULL)
  13917. {
  13918. if (mCurTypeInstance->mTypeFailed)
  13919. return;
  13920. if ((mCurTypeInstance->mTypeDef->GetDefinition()->mSource != NULL) && (mCurTypeInstance->mTypeDef->GetDefinition()->mSource->mParsingFailed))
  13921. return;
  13922. }
  13923. if (mCurMethodInstance != NULL)
  13924. {
  13925. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) &&
  13926. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  13927. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  13928. return;
  13929. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) &&
  13930. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  13931. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  13932. return;
  13933. }
  13934. if (mCompiler->IsAutocomplete())
  13935. return;
  13936. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  13937. }
  13938. void BfModule::AssertParseErrorState()
  13939. {
  13940. if (mCompiler->mRevision == 1)
  13941. AssertErrorState();
  13942. }
  13943. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  13944. {
  13945. BF_ASSERT(delegateType->IsDelegate());
  13946. auto typeInst = delegateType->ToTypeInstance();
  13947. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  13948. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  13949. if (invokeMethodInstance == NULL)
  13950. return GetPrimitiveType(BfTypeCode_Var);
  13951. return invokeMethodInstance->mReturnType;
  13952. }
  13953. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  13954. {
  13955. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  13956. }
  13957. void BfModule::CreateDelegateInvokeMethod()
  13958. {
  13959. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  13960. //mBfIRBuilder->ClearDebugLocation();
  13961. SetIllegalSrcPos();
  13962. auto typeInstance = mCurTypeInstance;
  13963. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  13964. SizedArray<BfIRType, 4> staticParamTypes;
  13965. SizedArray<BfIRValue, 4> staticFuncArgs;
  13966. SizedArray<BfIRValue, 4> memberFuncArgs;
  13967. auto multicastDelegateType = typeInstance->mBaseType;
  13968. if (multicastDelegateType->mFieldInstances.size() != 2)
  13969. {
  13970. AssertErrorState();
  13971. return;
  13972. }
  13973. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  13974. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  13975. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  13976. BfExprEvaluator exprEvaluator(this);
  13977. SizedArray<BfIRType, 8> origParamTypes;
  13978. BfIRType origReturnType;
  13979. BfIRType staticReturnType;
  13980. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  13981. if (mCurMethodInstance->mReturnType->IsValueType())
  13982. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  13983. if ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() != 0))
  13984. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  13985. int thisIdx = 0;
  13986. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13987. {
  13988. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  13989. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  13990. }
  13991. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  13992. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  13993. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == 0))
  13994. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  13995. mCurMethodInstance->GetIRFunctionInfo(this, staticReturnType, staticParamTypes, true);
  13996. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  13997. {
  13998. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  13999. exprEvaluator.PushArg(localVal, staticFuncArgs);
  14000. exprEvaluator.PushArg(localVal, memberFuncArgs);
  14001. }
  14002. auto staticFunc = mBfIRBuilder->CreateFunctionType(staticReturnType, staticParamTypes, false);
  14003. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  14004. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  14005. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  14006. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  14007. auto doneBB = mBfIRBuilder->CreateBlock("done");
  14008. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  14009. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  14010. BfIRValue nonStaticResult;
  14011. BfIRValue staticResult;
  14012. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  14013. /// Non-static invocation
  14014. {
  14015. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  14016. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  14017. mBfIRBuilder->SetInsertPoint(trueBB);
  14018. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  14019. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14020. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  14021. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  14022. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  14023. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14024. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  14025. if (callingConv != BfIRCallingConv_CDecl)
  14026. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  14027. mCurMethodState->SetHadReturn(false);
  14028. mCurMethodState->mLeftBlockUncond = false;
  14029. mCurMethodState->mLeftBlockCond = false;
  14030. mBfIRBuilder->CreateBr(doneBB);
  14031. }
  14032. // Static invocation
  14033. {
  14034. mBfIRBuilder->AddBlock(falseBB);
  14035. mBfIRBuilder->SetInsertPoint(falseBB);
  14036. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14037. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  14038. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  14039. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  14040. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14041. {
  14042. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  14043. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  14044. }
  14045. // We had a sret for the non-static but no sret for the static (because we have a lowered return type there)
  14046. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1) && (mCurMethodInstance->GetStructRetIdx(true) == -1))
  14047. {
  14048. auto sretToType = mBfIRBuilder->GetPointerTo(staticReturnType);
  14049. auto sretCastedPtr = mBfIRBuilder->CreateBitCast(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), sretToType);
  14050. mBfIRBuilder->CreateStore(staticResult, sretCastedPtr);
  14051. }
  14052. if (callingConv == BfIRCallingConv_ThisCall)
  14053. callingConv = BfIRCallingConv_CDecl;
  14054. if (callingConv != BfIRCallingConv_CDecl)
  14055. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  14056. mCurMethodState->SetHadReturn(false);
  14057. mCurMethodState->mLeftBlockUncond = false;
  14058. mCurMethodState->mLeftBlockCond = false;
  14059. mBfIRBuilder->CreateBr(doneBB);
  14060. }
  14061. mBfIRBuilder->AddBlock(doneBB);
  14062. mBfIRBuilder->SetInsertPoint(doneBB);
  14063. if (mCurMethodInstance->mReturnType->IsVar())
  14064. {
  14065. // Do nothing
  14066. }
  14067. else if ((mCurMethodInstance->mReturnType->IsValuelessType()) ||
  14068. ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1)))
  14069. {
  14070. mBfIRBuilder->CreateRetVoid();
  14071. }
  14072. else
  14073. {
  14074. BfIRType loweredIRReturnType;
  14075. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14076. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14077. if ((!mIsComptimeModule) && (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2)))
  14078. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  14079. else
  14080. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  14081. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  14082. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  14083. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  14084. mBfIRBuilder->CreateRet(phi);
  14085. }
  14086. }
  14087. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  14088. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  14089. {
  14090. auto typeDef = typeInstance->mTypeDef;
  14091. auto methodDeclaration = methodDef->mMethodDeclaration;
  14092. if (!mCompiler->mIsResolveOnly)
  14093. return true;
  14094. if (typeInstance->IsGenericTypeInstance())
  14095. {
  14096. // We only really want to process the unspecialized type for autocompletion
  14097. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  14098. return false;
  14099. }
  14100. BfAstNode* checkNode = methodDeclaration;
  14101. if (methodDeclaration == NULL)
  14102. checkNode = methodDef->mBody;
  14103. if ((!mCompiler->mResolvePassData->mParsers.IsEmpty()) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParsers[0])))
  14104. {
  14105. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  14106. return true;
  14107. }
  14108. return false;
  14109. }
  14110. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  14111. {
  14112. methodInst->mAppendAllocAlign = 1;
  14113. }
  14114. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  14115. {
  14116. BP_ZONE("BfModule::TryConstCalcAppend");
  14117. BF_ASSERT(methodInst->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  14118. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  14119. return BfTypedValue();
  14120. // We want to regenerate all ctor calls when the method internals change
  14121. {
  14122. auto checkTypeInst = methodInst->GetOwner();
  14123. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  14124. {
  14125. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  14126. checkTypeInst = GetBaseType(checkTypeInst);
  14127. }
  14128. }
  14129. if (!methodInst->mMayBeConst)
  14130. return BfTypedValue();
  14131. // Do we need to iterate in order to resolve mAppendAllocAlign?
  14132. bool isFirstRun = methodInst->mEndingAppendAllocAlign < 0;
  14133. bool wasAllConst = true;
  14134. int argIdx = 0;
  14135. int paramIdx = 0;
  14136. while (true)
  14137. {
  14138. if (argIdx >= (int)args.size())
  14139. break;
  14140. auto paramType = methodInst->GetParamType(paramIdx);
  14141. PopulateType(paramType);
  14142. int argCount = 0;
  14143. if (!paramType->IsValuelessType())
  14144. {
  14145. if ((!mIsComptimeModule) && (methodInst->GetParamIsSplat(paramIdx)))
  14146. argCount = paramType->GetSplatCount();
  14147. else
  14148. argCount = 1;
  14149. for (int argOfs = 0; argOfs < argCount; argOfs++)
  14150. {
  14151. auto arg = args[argIdx + argOfs];
  14152. if (!arg.IsConst())
  14153. {
  14154. wasAllConst = false;
  14155. if (!isFirstRun)
  14156. {
  14157. auto& param = methodInst->mParams[argIdx];
  14158. if (param.mReferencedInConstPass)
  14159. {
  14160. // If this param is required as part of the const calculation then
  14161. // we require that it be const...
  14162. return BfTypedValue();
  14163. }
  14164. }
  14165. }
  14166. }
  14167. }
  14168. paramIdx++;
  14169. argIdx += argCount;
  14170. }
  14171. auto methodDef = methodInst->mMethodDef;
  14172. auto methodDecl = methodDef->GetMethodDeclaration();
  14173. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14174. if (methodDeclBlock == NULL)
  14175. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  14176. BfTypedValue constValue;
  14177. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  14178. auto checkState = mCurMethodState->mConstResolveState;
  14179. while (checkState != NULL)
  14180. {
  14181. if (checkState->mMethodInstance == methodInst)
  14182. {
  14183. return BfTypedValue();
  14184. }
  14185. checkState = checkState->mPrevConstResolveState;
  14186. }
  14187. //auto accumValue = GetConstValue(0);
  14188. bool failed = false;
  14189. //
  14190. {
  14191. BfConstResolveState constResolveState;
  14192. constResolveState.mMethodInstance = methodInst;
  14193. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  14194. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14195. BfMethodState methodState;
  14196. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  14197. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  14198. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  14199. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  14200. methodState.mConstResolveState = &constResolveState;
  14201. int argIdx = 0;
  14202. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14203. {
  14204. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  14205. continue;
  14206. auto paramType = methodInst->GetParamType(paramIdx);
  14207. // Fix this after we allow structs to be consts
  14208. //BF_ASSERT(!paramType->IsSplattable());
  14209. BfLocalVariable* localVar = new BfLocalVariable();
  14210. localVar->mName = methodInst->GetParamName(paramIdx);
  14211. localVar->mResolvedType = paramType;
  14212. localVar->mConstValue = args[argIdx];
  14213. localVar->mParamIdx = paramIdx;
  14214. AddLocalVariableDef(localVar);
  14215. argIdx++;
  14216. }
  14217. AppendAllocVisitor appendAllocVisitor;
  14218. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  14219. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  14220. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  14221. if (baseCtorAppendValue)
  14222. {
  14223. if (baseCtorAppendValue.mValue.IsFake())
  14224. appendAllocVisitor.mFailed = true;
  14225. else
  14226. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  14227. }
  14228. appendAllocVisitor.mModule = this;
  14229. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14230. if (!appendAllocVisitor.mFailed)
  14231. constValue = appendAllocVisitor.mConstAccum;
  14232. if (isFirstRun)
  14233. {
  14234. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  14235. if (mCurMethodInstance->mAppendAllocAlign <= 0)
  14236. mCurMethodInstance->mAppendAllocAlign = 1;
  14237. }
  14238. if (isFirstRun)
  14239. {
  14240. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14241. {
  14242. auto localVar = mCurMethodState->mLocals[paramIdx];
  14243. if (localVar->mReadFromId != -1)
  14244. {
  14245. auto& param = methodInst->mParams[paramIdx];
  14246. param.mReferencedInConstPass = true;
  14247. }
  14248. }
  14249. }
  14250. }
  14251. mBfIRBuilder->SetInsertPoint(prevBlock);
  14252. if (!constValue)
  14253. {
  14254. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  14255. // all-const args
  14256. if (wasAllConst)
  14257. {
  14258. methodInst->mMayBeConst = false;
  14259. }
  14260. }
  14261. return constValue;
  14262. }
  14263. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  14264. {
  14265. // Any errors should only be shown in the actual CTOR call
  14266. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  14267. auto methodDef = mCurMethodInstance->mMethodDef;
  14268. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  14269. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  14270. BfCustomAttributes* customAttributes = NULL;
  14271. defer(delete customAttributes);
  14272. BfInvocationExpression* ctorInvocation = NULL;
  14273. if (ctorDeclaration != NULL)
  14274. {
  14275. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  14276. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  14277. {
  14278. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  14279. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  14280. }
  14281. }
  14282. BfTypeInstance* targetType = NULL;
  14283. if (ctorInvocation != NULL)
  14284. {
  14285. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  14286. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  14287. }
  14288. else
  14289. targetType = mCurTypeInstance->mBaseType;
  14290. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  14291. return NULL;
  14292. auto targetRefNode = methodDef->GetRefNode();
  14293. BfType* targetThisType = targetType;
  14294. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  14295. BfExprEvaluator exprEvaluator(this);
  14296. BfResolvedArgs argValues;
  14297. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  14298. {
  14299. argValues.Init(&ctorInvocation->mArguments);
  14300. }
  14301. //
  14302. {
  14303. }
  14304. BfFunctionBindResult bindResult;
  14305. bindResult.mSkipThis = true;
  14306. bindResult.mWantsArgs = true;
  14307. {
  14308. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14309. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14310. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14311. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  14312. }
  14313. if (bindResult.mMethodInstance == NULL)
  14314. {
  14315. AssertErrorState();
  14316. return BfTypedValue();
  14317. }
  14318. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  14319. {
  14320. return BfTypedValue();
  14321. }
  14322. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14323. bindResult.mIRArgs.RemoveAt(0);
  14324. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  14325. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  14326. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  14327. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  14328. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  14329. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  14330. if (appendSizeTypedValue)
  14331. return appendSizeTypedValue;
  14332. if (constOnly)
  14333. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  14334. bool needsRecalc = false;
  14335. for (auto irArg : bindResult.mIRArgs)
  14336. {
  14337. if (irArg.IsFake())
  14338. needsRecalc = true;
  14339. }
  14340. auto calcAppendArgs = bindResult.mIRArgs;
  14341. if (needsRecalc)
  14342. {
  14343. // Do it again, but without mIgnoreWrites set
  14344. BfResolvedArgs argValues;
  14345. argValues.Init(&ctorInvocation->mArguments);
  14346. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14347. BfFunctionBindResult bindResult;
  14348. bindResult.mSkipThis = true;
  14349. bindResult.mWantsArgs = true;
  14350. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14351. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  14352. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14353. bindResult.mIRArgs.RemoveAt(0);
  14354. calcAppendArgs = bindResult.mIRArgs;
  14355. }
  14356. BF_ASSERT(calcAppendMethodModule.mFunc);
  14357. appendSizeTypedValue = exprEvaluator.CreateCall(NULL, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  14358. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  14359. return appendSizeTypedValue;
  14360. }
  14361. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  14362. void BfModule::EmitCtorCalcAppend()
  14363. {
  14364. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  14365. return;
  14366. auto methodDef = mCurMethodInstance->mMethodDef;
  14367. auto methodDecl = methodDef->GetMethodDeclaration();
  14368. Array<BfAstNode*> deferredNodeList;
  14369. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14370. if (methodDeclBlock == NULL)
  14371. return;
  14372. AppendAllocVisitor appendAllocVisitor;
  14373. auto baseCalcAppend = CallBaseCtorCalc(false);
  14374. if (baseCalcAppend)
  14375. {
  14376. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  14377. }
  14378. appendAllocVisitor.mModule = this;
  14379. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14380. }
  14381. void BfModule::CreateStaticCtor()
  14382. {
  14383. auto typeDef = mCurTypeInstance->mTypeDef;
  14384. auto methodDef = mCurMethodInstance->mMethodDef;
  14385. BfIRBlock exitBB;
  14386. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  14387. {
  14388. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  14389. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  14390. mBfIRBuilder->MapType(boolType),
  14391. false,
  14392. BfIRLinkageType_Internal,
  14393. GetDefaultValue(boolType),
  14394. "didStaticInit");
  14395. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  14396. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14397. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  14398. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  14399. mBfIRBuilder->SetInsertPoint(initBB);
  14400. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  14401. }
  14402. // Do DLL imports
  14403. if (!mDllImportEntries.empty())
  14404. {
  14405. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  14406. PopulateType(internalType);
  14407. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  14408. if (!getSharedProcAddressInstance)
  14409. {
  14410. if (!mCompiler->mPassInstance->HasFailed())
  14411. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  14412. }
  14413. }
  14414. // Fill in initializer values
  14415. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  14416. {
  14417. for (auto fieldDef : typeDef->mFields)
  14418. {
  14419. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  14420. {
  14421. // For extensions, only handle these fields in the appropriate extension
  14422. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14423. continue;
  14424. UpdateSrcPos(fieldDef->mInitializer);
  14425. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  14426. if (!fieldInst->mFieldIncluded)
  14427. continue;
  14428. if (fieldInst->mResolvedType->IsVar())
  14429. {
  14430. continue;
  14431. }
  14432. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  14433. }
  14434. }
  14435. auto _CheckInitBlock = [&](BfAstNode* node)
  14436. {
  14437. };
  14438. EmitInitBlocks(_CheckInitBlock);
  14439. }
  14440. else
  14441. {
  14442. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  14443. {
  14444. if (tempTypeDef->mFullName == typeDef->mFullName)
  14445. {
  14446. for (auto fieldDef : tempTypeDef->mFields)
  14447. {
  14448. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  14449. {
  14450. if (fieldDef->mInitializer != NULL)
  14451. {
  14452. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDef->mInitializer))
  14453. {
  14454. sourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  14455. sourceClassifier->VisitChild(fieldDef->mInitializer);
  14456. }
  14457. BfType* wantType = NULL;
  14458. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  14459. {
  14460. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  14461. }
  14462. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  14463. }
  14464. }
  14465. }
  14466. }
  14467. }
  14468. }
  14469. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14470. CallChainedMethods(mCurMethodInstance, false);
  14471. }
  14472. void BfModule::EmitDtorBody()
  14473. {
  14474. if (!mCurMethodState->mIRExitBlock)
  14475. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14476. if (mCurTypeInstance->IsClosure())
  14477. {
  14478. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  14479. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  14480. auto thisVal = GetThis();
  14481. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  14482. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  14483. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  14484. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  14485. SizedArray<BfIRValue, 1> args;
  14486. args.push_back(thisVal.mValue);
  14487. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  14488. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  14489. // Fall through to Object::~this call
  14490. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  14491. if (mIsComptimeModule)
  14492. mCompiler->mCeMachine->QueueMethod(dtorFunc.mMethodInstance, dtorFunc.mFunc);
  14493. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  14494. SizedArray<BfIRValue, 1> vals = { basePtr };
  14495. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  14496. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  14497. mBfIRBuilder->SetTailCall(result);
  14498. return;
  14499. }
  14500. auto typeDef = mCurTypeInstance->mTypeDef;
  14501. auto methodDef = mCurMethodInstance->mMethodDef;
  14502. auto methodDeclaration = methodDef->GetMethodDeclaration();
  14503. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14504. CallChainedMethods(mCurMethodInstance, true);
  14505. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14506. {
  14507. VisitEmbeddedStatement(bodyBlock);
  14508. if (bodyBlock->mCloseBrace != NULL)
  14509. {
  14510. UpdateSrcPos(bodyBlock->mCloseBrace);
  14511. }
  14512. }
  14513. else
  14514. {
  14515. if (methodDeclaration != NULL)
  14516. UpdateSrcPos(methodDeclaration);
  14517. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  14518. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  14519. else if (typeDef->mTypeDeclaration != NULL)
  14520. UpdateSrcPos(typeDef->mTypeDeclaration);
  14521. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  14522. {
  14523. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  14524. }
  14525. }
  14526. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  14527. {
  14528. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  14529. {
  14530. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  14531. auto fieldDef = fieldInst->GetFieldDef();
  14532. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  14533. {
  14534. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  14535. {
  14536. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  14537. continue;
  14538. }
  14539. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  14540. {
  14541. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken, true);
  14542. }
  14543. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  14544. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  14545. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  14546. continue;
  14547. UpdateSrcPos(fieldDtor);
  14548. BfScopeData scopeData;
  14549. mCurMethodState->AddScope(&scopeData);
  14550. NewScopeState();
  14551. UpdateSrcPos(fieldDtor);
  14552. bool hasDbgInfo = (!fieldDef->mIsConst);
  14553. if (hasDbgInfo)
  14554. {
  14555. mBfIRBuilder->SaveDebugLocation();
  14556. mBfIRBuilder->ClearDebugLocation();
  14557. }
  14558. BfIRValue value;
  14559. if (fieldDef->mIsStatic)
  14560. {
  14561. value = ReferenceStaticField(fieldInst).mValue;
  14562. }
  14563. else
  14564. {
  14565. PopulateType(fieldInst->mResolvedType);
  14566. if (fieldInst->mResolvedType->IsValuelessType())
  14567. {
  14568. value = mBfIRBuilder->GetFakeVal();
  14569. }
  14570. else if (!mCurTypeInstance->IsValueType())
  14571. {
  14572. auto thisValue = GetThis();
  14573. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  14574. }
  14575. else
  14576. {
  14577. AssertErrorState();
  14578. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  14579. }
  14580. }
  14581. BfIRValue staticVal;
  14582. if (hasDbgInfo)
  14583. {
  14584. BfIRValue dbgShowValue = value;
  14585. BfLocalVariable* localDef = new BfLocalVariable();
  14586. localDef->mName = "_";
  14587. localDef->mResolvedType = fieldInst->mResolvedType;
  14588. localDef->mAddr = value;
  14589. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  14590. {
  14591. // Create another pointer indirection, a ref to the gep
  14592. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  14593. auto allocaInst = CreateAlloca(refFieldType);
  14594. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  14595. localDef->mResolvedType = refFieldType;
  14596. localDef->mAddr = allocaInst;
  14597. }
  14598. mBfIRBuilder->RestoreDebugLocation();
  14599. auto defLocalVar = AddLocalVariableDef(localDef, true);
  14600. // Put back so we actually modify the correct value*/
  14601. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  14602. defLocalVar->mAddr = value;
  14603. }
  14604. while (fieldDtor != NULL)
  14605. {
  14606. if (mCompiler->mResolvePassData != NULL)
  14607. {
  14608. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  14609. {
  14610. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  14611. sourceClassifier->VisitChild(fieldDtor);
  14612. }
  14613. }
  14614. UpdateSrcPos(fieldDtor);
  14615. VisitEmbeddedStatement(fieldDtor->mBody);
  14616. fieldDtor = fieldDtor->mNextFieldDtor;
  14617. }
  14618. RestoreScopeState();
  14619. }
  14620. }
  14621. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  14622. {
  14623. auto checkBaseType = mCurTypeInstance->mBaseType;
  14624. while (checkBaseType != NULL)
  14625. {
  14626. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14627. {
  14628. if (bodyBlock->mCloseBrace != NULL)
  14629. UpdateSrcPos(bodyBlock->mCloseBrace);
  14630. }
  14631. else
  14632. {
  14633. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  14634. }
  14635. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  14636. if (dtorMethodDef != NULL)
  14637. {
  14638. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  14639. if (IsSkippingExtraResolveChecks())
  14640. {
  14641. // Nothing
  14642. }
  14643. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  14644. {
  14645. if ((!IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  14646. {
  14647. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  14648. SizedArray<BfIRValue, 1> vals = { basePtr };
  14649. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  14650. if (mIsComptimeModule)
  14651. mCompiler->mCeMachine->QueueMethod(dtorMethodInstance.mMethodInstance, dtorMethodInstance.mFunc);
  14652. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  14653. }
  14654. }
  14655. else
  14656. {
  14657. // Invalid base dtor declaration
  14658. AssertErrorState();
  14659. }
  14660. break;
  14661. }
  14662. checkBaseType = checkBaseType->mBaseType;
  14663. }
  14664. }
  14665. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14666. }
  14667. else
  14668. {
  14669. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  14670. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  14671. // resolve pass, NOT the autocomplete expression
  14672. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  14673. {
  14674. if (tempTypeDef->mFullName == typeDef->mFullName)
  14675. {
  14676. for (auto fieldDef : tempTypeDef->mFields)
  14677. {
  14678. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  14679. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  14680. {
  14681. BfType* fieldType = NULL;
  14682. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  14683. {
  14684. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  14685. auto curFieldDef = curFieldInstance->GetFieldDef();
  14686. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  14687. fieldType = curFieldInstance->GetResolvedType();
  14688. }
  14689. if (fieldType == NULL)
  14690. fieldType = GetPrimitiveType(BfTypeCode_Var);
  14691. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  14692. BfScopeData scopeData;
  14693. mCurMethodState->AddScope(&scopeData);
  14694. NewScopeState();
  14695. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  14696. if (fieldType != NULL)
  14697. {
  14698. BfLocalVariable* localDef = new BfLocalVariable();
  14699. localDef->mName = "_";
  14700. localDef->mResolvedType = fieldType;
  14701. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  14702. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14703. AddLocalVariableDef(localDef);
  14704. }
  14705. while (fieldDtor != NULL)
  14706. {
  14707. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  14708. {
  14709. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  14710. sourceClassifier->VisitChild(fieldDtor);
  14711. }
  14712. UpdateSrcPos(fieldDtor);
  14713. VisitEmbeddedStatement(fieldDtor->mBody);
  14714. fieldDtor = fieldDtor->mNextFieldDtor;
  14715. }
  14716. RestoreScopeState();
  14717. }
  14718. }
  14719. }
  14720. }
  14721. }
  14722. }
  14723. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  14724. {
  14725. BF_ASSERT(methodInstance->mIsReified);
  14726. auto typeInstance = methodInstance->GetOwner();
  14727. bool foundDllImportAttr = false;
  14728. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  14729. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14730. {
  14731. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14732. {
  14733. foundDllImportAttr = true;
  14734. }
  14735. }
  14736. if (!foundDllImportAttr)
  14737. {
  14738. AssertErrorState();
  14739. return BfIRValue();
  14740. }
  14741. String name = "bf_hs_preserve@";
  14742. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  14743. name += "__imp";
  14744. BfIRType returnType;
  14745. SizedArray<BfIRType, 8> paramTypes;
  14746. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  14747. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  14748. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  14749. BfIRValue initVal;
  14750. if (define)
  14751. {
  14752. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  14753. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  14754. }
  14755. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  14756. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  14757. {
  14758. auto voidType = GetPrimitiveType(BfTypeCode_None);
  14759. auto ptrType = CreatePointerType(voidType);
  14760. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  14761. }
  14762. return globalVar;
  14763. }
  14764. void BfModule::CreateDllImportMethod()
  14765. {
  14766. if (mBfIRBuilder->mIgnoreWrites)
  14767. return;
  14768. auto globalVar = mFuncReferences[mCurMethodInstance];
  14769. if (!globalVar)
  14770. return;
  14771. bool allowTailCall = true;
  14772. mBfIRBuilder->ClearDebugLocation();
  14773. bool isHotCompile = mCompiler->IsHotCompile();
  14774. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  14775. if (isHotCompile)
  14776. {
  14777. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  14778. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  14779. }
  14780. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  14781. BfIRType returnType;
  14782. SizedArray<BfIRType, 8> paramTypes;
  14783. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  14784. SizedArray<BfIRValue, 8> args;
  14785. for (int i = 0; i < (int)paramTypes.size(); i++)
  14786. args.push_back(mBfIRBuilder->GetArgument(i));
  14787. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  14788. if (isHotCompile)
  14789. {
  14790. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  14791. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  14792. if (callingConvention == BfIRCallingConv_StdCall)
  14793. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  14794. else if (callingConvention == BfIRCallingConv_FastCall)
  14795. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  14796. else
  14797. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  14798. if (allowTailCall)
  14799. mBfIRBuilder->SetTailCall(result);
  14800. CreateReturn(result);
  14801. mCurMethodState->mHadReturn = true;
  14802. }
  14803. if (HasCompiledOutput())
  14804. {
  14805. BfDllImportEntry dllImportEntry;
  14806. dllImportEntry.mFuncVar = globalVar;
  14807. dllImportEntry.mMethodInstance = mCurMethodInstance;
  14808. mDllImportEntries.push_back(dllImportEntry);
  14809. }
  14810. }
  14811. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  14812. {
  14813. auto methodDef = methodInstance->mMethodDef;
  14814. BfTypeInstance* owner = NULL;
  14815. if (!methodDef->mIsStatic)
  14816. owner = methodInstance->GetThisType()->ToTypeInstance();
  14817. if (owner == NULL)
  14818. owner = methodInstance->GetOwner();
  14819. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  14820. return BfIRCallingConv_CDecl;
  14821. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  14822. return BfIRCallingConv_StdCall;
  14823. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  14824. return BfIRCallingConv_FastCall;
  14825. if (!methodDef->mIsStatic)
  14826. {
  14827. if (owner->mIsCRepr)
  14828. return BfIRCallingConv_ThisCall;
  14829. if ((!owner->IsValuelessType()) &&
  14830. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  14831. return BfIRCallingConv_ThisCall;
  14832. }
  14833. return BfIRCallingConv_CDecl;
  14834. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  14835. }
  14836. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  14837. {
  14838. BfMethodDef* methodDef = NULL;
  14839. if (methodInstance != NULL)
  14840. methodDef = methodInstance->mMethodDef;
  14841. if (!func)
  14842. return;
  14843. if (mCompiler->mOptions.mNoFramePointerElim)
  14844. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  14845. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  14846. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  14847. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  14848. if (methodInstance == NULL)
  14849. return;
  14850. if (methodInstance->mReturnType->IsVar())
  14851. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_VarRet);
  14852. if (methodDef->mImportKind == BfImportKind_Export)
  14853. {
  14854. if (methodDef->mDeclaringType->mProject->mTargetType != BfTargetType_BeefLib_StaticLib)
  14855. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  14856. }
  14857. if (methodDef->mIsNoReturn)
  14858. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  14859. auto callingConv = GetIRCallingConvention(methodInstance);
  14860. if (callingConv != BfIRCallingConv_CDecl)
  14861. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  14862. if (isInlined)
  14863. {
  14864. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  14865. }
  14866. int argIdx = 0;
  14867. int paramIdx = 0;
  14868. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  14869. paramIdx = -1;
  14870. int argCount = methodInstance->GetIRFunctionParamCount(this);
  14871. while (argIdx < argCount)
  14872. {
  14873. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  14874. {
  14875. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  14876. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  14877. argIdx++;
  14878. continue;
  14879. }
  14880. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  14881. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  14882. paramIdx++;
  14883. BfType* resolvedTypeRef = NULL;
  14884. BfType* resolvedTypeRef2 = NULL;
  14885. String paramName;
  14886. bool isSplattable = false;
  14887. bool tryLowering = !mIsComptimeModule;
  14888. if (isThis)
  14889. {
  14890. paramName = "this";
  14891. if (methodInstance->mIsClosure)
  14892. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  14893. else
  14894. resolvedTypeRef = methodInstance->GetThisType();
  14895. isSplattable = (!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(-1));
  14896. tryLowering = (!mIsComptimeModule) && (methodInstance->AllowsSplatting(-1));
  14897. }
  14898. else
  14899. {
  14900. paramName = methodInstance->GetParamName(paramIdx);
  14901. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  14902. if (resolvedTypeRef->IsMethodRef())
  14903. isSplattable = true;
  14904. else if ((!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(paramIdx)))
  14905. {
  14906. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  14907. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  14908. {
  14909. // crepr splat is always splattable
  14910. isSplattable = true;
  14911. }
  14912. else
  14913. {
  14914. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  14915. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  14916. isSplattable = true;
  14917. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  14918. isSplattable = true;
  14919. }
  14920. }
  14921. }
  14922. if (tryLowering)
  14923. {
  14924. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14925. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14926. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  14927. {
  14928. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  14929. argIdx++;
  14930. if (loweredTypeCode2 != BfTypeCode_None)
  14931. {
  14932. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  14933. argIdx++;
  14934. }
  14935. paramIdx++;
  14936. continue;
  14937. }
  14938. }
  14939. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  14940. {
  14941. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  14942. int addDeref = -1;
  14943. if (resolvedTypeRef->IsRef())
  14944. {
  14945. auto refType = (BfRefType*)resolvedTypeRef;
  14946. auto elementType = refType->mElementType;
  14947. PopulateType(elementType, BfPopulateType_Data);
  14948. addDeref = elementType->mSize;
  14949. if ((addDeref <= 0) && (!elementType->IsValuelessType()) && (!elementType->IsOpaque()))
  14950. AssertErrorState();
  14951. }
  14952. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  14953. {
  14954. if (isThis)
  14955. {
  14956. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  14957. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  14958. addDeref = resolvedTypeRef->mSize;
  14959. }
  14960. else if (methodInstance->WantsStructsAttribByVal(resolvedTypeRef))
  14961. {
  14962. mBfIRBuilder->PopulateType(resolvedTypeRef, BfIRPopulateType_Full);
  14963. BF_ASSERT(resolvedTypeRef->mAlign > 0);
  14964. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  14965. }
  14966. }
  14967. else if (resolvedTypeRef->IsPrimitiveType())
  14968. {
  14969. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  14970. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  14971. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  14972. }
  14973. if (addDeref >= 0)
  14974. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  14975. argIdx++;
  14976. };
  14977. if (isSplattable)
  14978. {
  14979. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  14980. {
  14981. if (checkType->IsStruct())
  14982. {
  14983. auto checkTypeInstance = checkType->ToTypeInstance();
  14984. if (checkTypeInstance->mBaseType != NULL)
  14985. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  14986. if (checkTypeInstance->mIsUnion)
  14987. {
  14988. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  14989. checkTypeLambda(unionInnerType, curName + "_data");
  14990. }
  14991. else
  14992. {
  14993. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14994. {
  14995. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14996. auto fieldDef = fieldInstance->GetFieldDef();
  14997. if (fieldInstance->mDataIdx >= 0)
  14998. {
  14999. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  15000. }
  15001. }
  15002. }
  15003. if (checkTypeInstance->IsEnum())
  15004. {
  15005. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  15006. argIdx++;
  15007. }
  15008. }
  15009. else if (checkType->IsMethodRef())
  15010. {
  15011. auto methodRefType = (BfMethodRefType*)checkType;
  15012. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  15013. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  15014. {
  15015. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  15016. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  15017. {
  15018. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  15019. }
  15020. else
  15021. {
  15022. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  15023. }
  15024. }
  15025. }
  15026. else if (!checkType->IsValuelessType())
  15027. {
  15028. _SetupParam(curName, checkType);
  15029. }
  15030. };
  15031. checkTypeLambda(resolvedTypeRef, paramName);
  15032. paramIdx++;
  15033. continue;
  15034. }
  15035. _SetupParam(paramName, resolvedTypeRef);
  15036. if (resolvedTypeRef2 != NULL)
  15037. _SetupParam(paramName, resolvedTypeRef2);
  15038. paramIdx++;
  15039. }
  15040. }
  15041. void BfModule::EmitInitBlocks(const std::function<void(BfAstNode*)>& initBlockCallback)
  15042. {
  15043. auto methodDef = mCurMethodInstance->mMethodDef;
  15044. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  15045. BfMemberSetEntry* entry = NULL;
  15046. BfMethodDef* initMethodDef = NULL;
  15047. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  15048. if (entry != NULL)
  15049. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  15050. SizedArray<BfAstNode*, 8> initBodies;
  15051. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  15052. {
  15053. if (initMethodDef->mDeclaringType->GetDefinition() != methodDef->mDeclaringType->GetDefinition())
  15054. continue;
  15055. if (initMethodDef->mMethodType != BfMethodType_Init)
  15056. continue;
  15057. if (initMethodDef->mIsStatic != methodDef->mIsStatic)
  15058. continue;
  15059. initBodies.Insert(0, initMethodDef->mBody);
  15060. }
  15061. for (auto body : initBodies)
  15062. {
  15063. initBlockCallback(body);
  15064. VisitEmbeddedStatement(body);
  15065. }
  15066. }
  15067. void BfModule::EmitCtorBody(bool& skipBody)
  15068. {
  15069. auto methodInstance = mCurMethodInstance;
  15070. auto methodDef = methodInstance->mMethodDef;
  15071. auto methodDeclaration = methodDef->mMethodDeclaration;
  15072. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  15073. auto typeDef = mCurTypeInstance->mTypeDef;
  15074. BfCustomAttributes* customAttributes = NULL;
  15075. defer(delete customAttributes);
  15076. BfInvocationExpression* ctorInvocation = NULL;
  15077. BfAttributeState attributeState;
  15078. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  15079. if (ctorDeclaration != NULL)
  15080. {
  15081. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  15082. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  15083. {
  15084. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  15085. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  15086. }
  15087. }
  15088. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  15089. // Prologue
  15090. mBfIRBuilder->ClearDebugLocation();
  15091. bool hadThisInitializer = false;
  15092. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15093. {
  15094. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15095. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15096. if (targetToken->GetToken() == BfToken_This)
  15097. {
  15098. hadThisInitializer = true;
  15099. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  15100. mCurMethodState->LocalDefined(GetThisVariable());
  15101. }
  15102. }
  15103. // Zero out memory for default ctor
  15104. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()) && (methodInstance->mChainType != BfMethodChainType_ChainMember))
  15105. {
  15106. if (mCurTypeInstance->IsTypedPrimitive())
  15107. {
  15108. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15109. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  15110. }
  15111. else if (mCurTypeInstance->mInstSize > 0)
  15112. {
  15113. BfIRValue fillValue = GetConstValue8(0);
  15114. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  15115. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15116. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  15117. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  15118. }
  15119. }
  15120. BfAstNode* baseCtorNode = NULL;
  15121. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  15122. baseCtorNode = ctorInvocation->mTarget;
  15123. else if (methodDef->mBody != NULL)
  15124. baseCtorNode = methodDef->mBody;
  15125. else if (ctorDeclaration != NULL)
  15126. baseCtorNode = ctorDeclaration;
  15127. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15128. baseCtorNode = methodDef->mDeclaringType->GetRefNode();
  15129. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15130. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  15131. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  15132. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  15133. else
  15134. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  15135. bool calledCtorNoBody = false;
  15136. if ((mCurTypeInstance->IsTypedPrimitive()) && (!mCurTypeInstance->IsValuelessType()))
  15137. {
  15138. // Zero out typed primitives in ctor
  15139. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance->GetUnderlyingType()), mBfIRBuilder->GetArgument(0));
  15140. }
  15141. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  15142. {
  15143. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  15144. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  15145. {
  15146. BfMethodDef* defaultCtor = NULL;
  15147. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  15148. {
  15149. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  15150. {
  15151. defaultCtor = methodDef;
  15152. }
  15153. }
  15154. if (defaultCtor != NULL)
  15155. {
  15156. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  15157. SetIllegalSrcPos();
  15158. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  15159. BfExprEvaluator exprEvaluator(this);
  15160. SizedArray<BfIRValue, 1> irArgs;
  15161. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  15162. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  15163. if (mIsComptimeModule)
  15164. mCompiler->mCeMachine->QueueMethod(moduleMethodInstance);
  15165. calledCtorNoBody = true;
  15166. }
  15167. }
  15168. }
  15169. // Initialize fields (if applicable)
  15170. if (mCurTypeInstance->IsBoxed())
  15171. {
  15172. skipBody = true;
  15173. }
  15174. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  15175. {
  15176. // Field initializers occur in CtorNoBody methods for extensions
  15177. }
  15178. else if (!hadThisInitializer)
  15179. {
  15180. // If we had a 'this' initializer, that other ctor will have initialized our fields
  15181. //auto
  15182. if ((!mCompiler->mIsResolveOnly) ||
  15183. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  15184. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  15185. {
  15186. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  15187. // to properly set the assigned flags
  15188. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  15189. bool hadInlineInitBlock = false;
  15190. BfScopeData scopeData;
  15191. scopeData.mInInitBlock = true;
  15192. auto _CheckInitBlock = [&](BfAstNode* node)
  15193. {
  15194. if (!hadInlineInitBlock)
  15195. {
  15196. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  15197. {
  15198. UpdateSrcPos(baseCtorNode);
  15199. if (methodDef->mBody == NULL)
  15200. SetIllegalSrcPos();
  15201. // 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
  15202. EmitEnsureInstructionAt();
  15203. BfType* thisType = mCurTypeInstance;
  15204. if (thisType->IsValueType())
  15205. thisType = CreateRefType(thisType);
  15206. SizedArray<BfIRMDNode, 1> diParamTypes;
  15207. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  15208. mCurMethodState->AddScope(&scopeData);
  15209. NewScopeState();
  15210. int flags = 0;
  15211. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  15212. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  15213. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  15214. String linkageName;
  15215. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mCurBuilder != NULL))
  15216. linkageName = StrFormat("%d", mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(mCurMethodInstance, "$initFields"));
  15217. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", linkageName, mCurFilePosition.mFileInstance->mDIFile,
  15218. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  15219. UpdateSrcPos(node);
  15220. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  15221. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  15222. //
  15223. {
  15224. auto loadedThis = GetThis();
  15225. // LLVM can't handle two variables pointing to the same value
  15226. BfIRValue copiedThisPtr;
  15227. copiedThisPtr = CreateAlloca(thisType);
  15228. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  15229. mBfIRBuilder->ClearDebugLocation(storeInst);
  15230. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  15231. }
  15232. hadInlineInitBlock = true;
  15233. }
  15234. else
  15235. {
  15236. // Just do a simple one
  15237. mCurMethodState->AddScope(&scopeData);
  15238. NewScopeState();
  15239. hadInlineInitBlock = true;
  15240. }
  15241. }
  15242. UpdateSrcPos(node);
  15243. };
  15244. for (auto fieldDef : typeDef->mFields)
  15245. {
  15246. // For extensions, only handle these fields in the appropriate extension
  15247. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15248. continue;
  15249. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  15250. {
  15251. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15252. if (!fieldInst->mFieldIncluded)
  15253. continue;
  15254. if (fieldInst->mDataIdx < 0)
  15255. continue;
  15256. if (fieldDef->mInitializer == NULL)
  15257. {
  15258. continue;
  15259. // if (fieldDef->mProtection != BfProtection_Hidden)
  15260. // continue;
  15261. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  15262. // continue;
  15263. }
  15264. if (fieldInst->mResolvedType == NULL)
  15265. {
  15266. BF_ASSERT(mHadBuildError);
  15267. continue;
  15268. }
  15269. if (fieldDef->mInitializer != NULL)
  15270. {
  15271. _CheckInitBlock(fieldDef->mInitializer);
  15272. }
  15273. BfIRValue fieldAddr;
  15274. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  15275. {
  15276. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  15277. }
  15278. else
  15279. {
  15280. // Failed
  15281. }
  15282. auto assignValue = GetFieldInitializerValue(fieldInst);
  15283. if (mCurTypeInstance->IsUnion())
  15284. {
  15285. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  15286. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  15287. }
  15288. if ((fieldAddr) && (assignValue))
  15289. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  15290. }
  15291. }
  15292. EmitInitBlocks(_CheckInitBlock);
  15293. if (hadInlineInitBlock)
  15294. {
  15295. RestoreScopeState();
  15296. // This gets set to false because of AddScope but we actually are still in the head block
  15297. mCurMethodState->mInHeadScope = true;
  15298. // Make sure we emit a return even if we had a NoReturn call or return inside ourselves
  15299. mCurMethodState->mHadReturn = false;
  15300. mCurMethodState->mLeftBlockUncond = false;
  15301. }
  15302. }
  15303. else // Autocomplete case
  15304. {
  15305. BfScopeData scopeData;
  15306. scopeData.mInInitBlock = true;
  15307. mCurMethodState->AddScope(&scopeData);
  15308. NewScopeState();
  15309. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15310. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15311. // resolve pass, NOT the autocomplete expression
  15312. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15313. {
  15314. if (tempTypeDef->mFullName == typeDef->mFullName)
  15315. {
  15316. for (auto fieldDef : tempTypeDef->mFields)
  15317. {
  15318. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  15319. {
  15320. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDef->mInitializer))
  15321. {
  15322. sourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  15323. sourceClassifier->VisitChild(fieldDef->mInitializer);
  15324. }
  15325. BfType* wantType = NULL;
  15326. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) &&
  15327. (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  15328. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowInferredSizedArray);
  15329. if ((wantType != NULL) &&
  15330. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  15331. wantType = NULL;
  15332. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  15333. }
  15334. }
  15335. tempTypeDef->PopulateMemberSets();
  15336. BfMemberSetEntry* entry = NULL;
  15337. BfMethodDef* initMethodDef = NULL;
  15338. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  15339. if (entry != NULL)
  15340. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  15341. SizedArray<BfAstNode*, 8> initBodies;
  15342. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  15343. {
  15344. if (initMethodDef->mMethodType != BfMethodType_Init)
  15345. continue;
  15346. initBodies.Insert(0, initMethodDef->mBody);
  15347. }
  15348. for (auto body : initBodies)
  15349. VisitEmbeddedStatement(body);
  15350. }
  15351. }
  15352. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  15353. for (auto fieldDef : typeDef->mFields)
  15354. {
  15355. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  15356. {
  15357. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15358. if (fieldDef->mInitializer != NULL)
  15359. MarkFieldInitialized(fieldInst);
  15360. }
  15361. }
  15362. RestoreScopeState();
  15363. }
  15364. }
  15365. if (!methodInstance->mIsAutocompleteMethod)
  15366. {
  15367. if (auto autoDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  15368. {
  15369. BfExprEvaluator exprEvaluator(this);
  15370. for (int paramIdx = 0; paramIdx < methodDef->mParams.mSize; paramIdx++)
  15371. {
  15372. auto paramDef = methodDef->mParams[paramIdx];
  15373. auto& fieldInstance = mCurTypeInstance->mFieldInstances[paramIdx];
  15374. BF_ASSERT(paramDef->mName == fieldInstance.GetFieldDef()->mName);
  15375. if (fieldInstance.mDataIdx < 0)
  15376. continue;
  15377. if (paramDef->mParamKind != BfParamKind_Normal)
  15378. continue;
  15379. auto localVar = mCurMethodState->mLocals[paramIdx + 1];
  15380. BF_ASSERT(localVar->mName == paramDef->mName);
  15381. auto localVal = exprEvaluator.LoadLocal(localVar);
  15382. localVal = LoadOrAggregateValue(localVal);
  15383. if (!localVal.mType->IsVar())
  15384. {
  15385. auto thisVal = GetThis();
  15386. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance.mDataIdx);
  15387. mBfIRBuilder->CreateAlignedStore(localVal.mValue, fieldPtr, localVar->mResolvedType->mAlign);
  15388. }
  15389. MarkFieldInitialized(&fieldInstance);
  15390. }
  15391. }
  15392. }
  15393. // Call base ctor (if applicable)
  15394. BfTypeInstance* targetType = NULL;
  15395. BfAstNode* targetRefNode = NULL;
  15396. if (ctorDeclaration != NULL)
  15397. targetRefNode = ctorDeclaration->mInitializer;
  15398. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  15399. targetRefNode = invocationExpr->mTarget;
  15400. if (baseCtorNode != NULL)
  15401. {
  15402. UpdateSrcPos(baseCtorNode);
  15403. if (methodDef->mBody == NULL)
  15404. SetIllegalSrcPos();
  15405. }
  15406. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15407. {
  15408. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15409. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15410. }
  15411. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()) && (methodDef->mMethodType != BfMethodType_CtorNoBody))
  15412. {
  15413. auto baseType = mCurTypeInstance->mBaseType;
  15414. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  15415. ((baseType->mTypeDef != mCompiler->mValueTypeTypeDef) || (!mContext->mCanSkipValueTypeCtor)) &&
  15416. ((baseType->mTypeDef != mCompiler->mBfObjectTypeDef) || (!mContext->mCanSkipObjectCtor)))
  15417. {
  15418. // Try to find a ctor without any params first
  15419. BfMethodDef* matchedMethod = NULL;
  15420. bool hadCtorWithAllDefaults = false;
  15421. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  15422. for (int pass = 0; pass < 2; pass++)
  15423. {
  15424. baseType->mTypeDef->PopulateMemberSets();
  15425. BfMemberSetEntry* entry = NULL;
  15426. BfMethodDef* checkMethodDef = NULL;
  15427. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  15428. if (entry != NULL)
  15429. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  15430. while (checkMethodDef != NULL)
  15431. {
  15432. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  15433. if (isHiddenGenerated)
  15434. {
  15435. // Allow calling of the default base ctor if it is implicitly defined
  15436. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  15437. allowMethod = true;
  15438. }
  15439. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  15440. {
  15441. if (checkMethodDef->mParams.size() == 0)
  15442. {
  15443. if (matchedMethod != NULL)
  15444. {
  15445. // Has multiple matched methods - can happen from extensions
  15446. matchedMethod = NULL;
  15447. break;
  15448. }
  15449. matchedMethod = checkMethodDef;
  15450. }
  15451. else if (isHiddenGenerated)
  15452. {
  15453. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  15454. hadCtorWithAllDefaults = true;
  15455. }
  15456. }
  15457. checkMethodDef = checkMethodDef->mNextWithSameName;
  15458. }
  15459. if (matchedMethod != NULL)
  15460. break;
  15461. }
  15462. if ((HasExecutedOutput()) && (matchedMethod != NULL))
  15463. {
  15464. SizedArray<BfIRValue, 1> args;
  15465. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  15466. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  15467. {
  15468. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  15469. args.push_back(basePtr);
  15470. }
  15471. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  15472. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  15473. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  15474. if (callingConv != BfIRCallingConv_CDecl)
  15475. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  15476. if (mIsComptimeModule)
  15477. mCompiler->mCeMachine->QueueMethod(ctorBodyMethodInstance);
  15478. }
  15479. if (matchedMethod == NULL)
  15480. {
  15481. targetType = mCurTypeInstance->mBaseType;
  15482. if (ctorDeclaration != NULL)
  15483. targetRefNode = ctorDeclaration->mThisToken;
  15484. else if (typeDef->mTypeDeclaration != NULL)
  15485. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  15486. }
  15487. }
  15488. }
  15489. if (methodDef->mHasAppend)
  15490. {
  15491. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  15492. }
  15493. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  15494. {
  15495. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  15496. {
  15497. if (targetType == mCurTypeInstance)
  15498. {
  15499. auto thisVariable = GetThisVariable();
  15500. if (thisVariable != NULL)
  15501. {
  15502. thisVariable->mUnassignedFieldFlags = 0;
  15503. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15504. }
  15505. }
  15506. targetType = NULL;
  15507. }
  15508. }
  15509. if (targetType != NULL)
  15510. {
  15511. BfAstNode* refNode = methodDeclaration;
  15512. if (refNode == NULL)
  15513. refNode = typeDef->mTypeDeclaration;
  15514. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  15515. auto autoComplete = mCompiler->GetAutoComplete();
  15516. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  15517. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15518. {
  15519. auto invocationExpr = ctorInvocation;
  15520. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  15521. }
  15522. BfType* targetThisType = targetType;
  15523. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  15524. BfExprEvaluator exprEvaluator(this);
  15525. BfResolvedArgs argValues;
  15526. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15527. {
  15528. argValues.Init(&ctorInvocation->mArguments);
  15529. if (gDebugStuff)
  15530. {
  15531. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  15532. }
  15533. }
  15534. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15535. BfTypedValue appendIdxVal;
  15536. if (methodDef->mHasAppend)
  15537. {
  15538. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  15539. BF_ASSERT(localVar->mName == "appendIdx");
  15540. auto intRefType = localVar->mResolvedType;
  15541. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  15542. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  15543. }
  15544. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  15545. if (autoComplete != NULL)
  15546. {
  15547. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  15548. {
  15549. if (autoComplete->mMethodMatchInfo != NULL)
  15550. autoComplete->mIsCapturingMethodMatchInfo = true;
  15551. else
  15552. autoComplete->mIsCapturingMethodMatchInfo = false;
  15553. }
  15554. else
  15555. autoComplete->mIsCapturingMethodMatchInfo = false;
  15556. }
  15557. }
  15558. }
  15559. void BfModule::EmitEnumToStringBody()
  15560. {
  15561. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  15562. auto strVal = CreateAlloca(stringType);
  15563. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  15564. BfExprEvaluator exprEvaluator(this);
  15565. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  15566. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  15567. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  15568. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  15569. BfType* discriminatorType = NULL;
  15570. BfTypedValue rawPayload;
  15571. BfIRValue enumVal;
  15572. if (mCurTypeInstance->IsPayloadEnum())
  15573. {
  15574. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  15575. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  15576. enumTypedValue = LoadValue(enumTypedValue);
  15577. enumVal = enumTypedValue.mValue;
  15578. rawPayload = ExtractValue(GetThis(), NULL, 1);
  15579. }
  15580. else
  15581. enumVal = mBfIRBuilder->GetArgument(0);
  15582. Array<BfType*> paramTypes;
  15583. paramTypes.Add(stringType);
  15584. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  15585. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  15586. HashSet<int64> handledCases;
  15587. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  15588. {
  15589. if (fieldInstance.mIsEnumPayloadCase)
  15590. {
  15591. int tagId = -fieldInstance.mDataIdx - 1;
  15592. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  15593. mBfIRBuilder->AddBlock(caseBlock);
  15594. mBfIRBuilder->SetInsertPoint(caseBlock);
  15595. BF_ASSERT(discriminatorType->IsPrimitiveType());
  15596. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  15597. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  15598. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  15599. auto stringDestVal = LoadValue(stringDestAddr);
  15600. SizedArray<BfIRValue, 2> args;
  15601. args.Add(stringDestVal.mValue);
  15602. args.Add(caseStr);
  15603. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  15604. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  15605. BF_ASSERT(payloadType->IsTuple());
  15606. if (payloadType->mFieldInstances.size() != 0)
  15607. {
  15608. auto payload = rawPayload;
  15609. if (payload.mType != payloadType)
  15610. {
  15611. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  15612. }
  15613. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  15614. SizedArray<BfIRValue, 2> irArgs;
  15615. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  15616. stringDestVal = LoadValue(stringDestAddr);
  15617. irArgs.Add(stringDestVal.mValue);
  15618. exprEvaluator.CreateCall(NULL, toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  15619. }
  15620. mBfIRBuilder->CreateBr(endBlock);
  15621. continue;
  15622. }
  15623. if (fieldInstance.mConstIdx == -1)
  15624. continue;
  15625. // Only allow compact 'ValA, ValB' enum declaration fields through
  15626. auto fieldDecl = fieldInstance.GetFieldDef()->mFieldDeclaration;
  15627. if ((fieldDecl == NULL) || (fieldDecl->mTypeRef != NULL))
  15628. continue;
  15629. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  15630. if (!handledCases.TryAdd(constant->mInt64, NULL))
  15631. {
  15632. // Duplicate
  15633. continue;
  15634. }
  15635. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  15636. mBfIRBuilder->AddBlock(caseBlock);
  15637. mBfIRBuilder->SetInsertPoint(caseBlock);
  15638. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  15639. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  15640. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  15641. mBfIRBuilder->CreateStore(caseStr, strVal);
  15642. mBfIRBuilder->CreateBr(appendBlock);
  15643. }
  15644. mBfIRBuilder->AddBlock(appendBlock);
  15645. mBfIRBuilder->SetInsertPoint(appendBlock);
  15646. SizedArray<BfIRValue, 2> args;
  15647. auto stringDestVal = LoadValue(stringDestAddr);
  15648. args.Add(stringDestVal.mValue);
  15649. args.Add(mBfIRBuilder->CreateLoad(strVal));
  15650. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  15651. mBfIRBuilder->CreateBr(endBlock);
  15652. mBfIRBuilder->AddBlock(noMatchBlock);
  15653. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  15654. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  15655. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  15656. args.clear();
  15657. args.Add(int64Val);
  15658. stringDestVal = LoadValue(stringDestAddr);
  15659. args.Add(stringDestVal.mValue);
  15660. exprEvaluator.CreateCall(NULL, toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  15661. mBfIRBuilder->CreateBr(endBlock);
  15662. mBfIRBuilder->AddBlock(endBlock);
  15663. mBfIRBuilder->SetInsertPoint(endBlock);
  15664. }
  15665. void BfModule::EmitTupleToStringBody()
  15666. {
  15667. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  15668. BfExprEvaluator exprEvaluator(this);
  15669. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  15670. Array<BfType*> paramTypes;
  15671. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  15672. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  15673. paramTypes.Clear();
  15674. paramTypes.Add(stringType);
  15675. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  15676. auto _AppendChar = [&](char c)
  15677. {
  15678. SizedArray<BfIRValue, 2> args;
  15679. auto stringDestVal = LoadValue(stringDestRef);
  15680. args.Add(stringDestVal.mValue);
  15681. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  15682. exprEvaluator.CreateCall(NULL, appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  15683. };
  15684. int fieldIdx = 0;
  15685. auto thisValue = GetThis();
  15686. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  15687. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  15688. BfIRValue commaStr;
  15689. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  15690. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  15691. _AppendChar('(');
  15692. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  15693. {
  15694. if (fieldInstance.mDataIdx == -1)
  15695. continue;
  15696. if (fieldIdx > 0)
  15697. {
  15698. if (!commaStr)
  15699. commaStr = GetStringObjectValue(", ");
  15700. SizedArray<BfIRValue, 2> args;
  15701. auto stringDestVal = LoadValue(stringDestRef);
  15702. args.Add(stringDestVal.mValue);
  15703. args.Add(commaStr);
  15704. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  15705. }
  15706. fieldIdx++;
  15707. if (fieldInstance.mResolvedType->IsValuelessType())
  15708. continue;
  15709. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  15710. if (fieldValue.mType->IsPrimitiveType())
  15711. {
  15712. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  15713. }
  15714. auto typeInstance = fieldValue.mType->ToTypeInstance();
  15715. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  15716. {
  15717. BfExprEvaluator exprEvaluator(this);
  15718. SizedArray<BfResolvedArg, 0> resolvedArgs;
  15719. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  15720. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  15721. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  15722. methodMatcher.TryDevirtualizeCall(fieldValue);
  15723. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  15724. BfResolvedArg resolvedArg;
  15725. auto stringDestVal = LoadValue(stringDestRef);
  15726. resolvedArg.mTypedValue = stringDestVal;
  15727. resolvedArg.mResolvedType = stringDestVal.mType;
  15728. resolvedArgs.Add(resolvedArg);
  15729. exprEvaluator.CreateCall(&methodMatcher, callVal);
  15730. continue;
  15731. }
  15732. if (fieldValue.mType->IsObjectOrInterface())
  15733. {
  15734. fieldValue = LoadValue(fieldValue);
  15735. BF_ASSERT(!fieldValue.IsAddr());
  15736. SizedArray<BfIRValue, 2> args;
  15737. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  15738. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  15739. stringDestVal = LoadValue(stringDestVal);
  15740. args.Add(stringDestVal.mValue);
  15741. exprEvaluator.CreateCall(NULL, toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  15742. continue;
  15743. }
  15744. BfExprEvaluator exprEvaluator(this);
  15745. SizedArray<BfResolvedArg, 0> resolvedArgs;
  15746. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  15747. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  15748. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  15749. methodMatcher.TryDevirtualizeCall(fieldValue);
  15750. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  15751. {
  15752. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  15753. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  15754. // Just append the type name
  15755. String typeName = TypeToString(fieldInstance.mResolvedType);
  15756. auto strVal = GetStringObjectValue(typeName);
  15757. SizedArray<BfIRValue, 2> args;
  15758. auto stringDestVal = LoadValue(stringDestRef);
  15759. args.Add(stringDestVal.mValue);
  15760. args.Add(strVal);
  15761. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  15762. continue;
  15763. }
  15764. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  15765. BfResolvedArg resolvedArg;
  15766. auto stringDestVal = LoadValue(stringDestRef);
  15767. resolvedArg.mTypedValue = stringDestVal;
  15768. resolvedArg.mResolvedType = stringDestVal.mType;
  15769. resolvedArgs.Add(resolvedArg);
  15770. exprEvaluator.CreateCall(&methodMatcher, callVal);
  15771. }
  15772. _AppendChar(')');
  15773. }
  15774. void BfModule::EmitIteratorBlock(bool& skipBody)
  15775. {
  15776. auto methodInstance = mCurMethodInstance;
  15777. auto methodDef = methodInstance->mMethodDef;
  15778. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15779. auto typeDef = mCurTypeInstance->mTypeDef;
  15780. BfType* innerRetType = NULL;
  15781. BfTypeInstance* usingInterface = NULL;
  15782. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  15783. if (retTypeInst != NULL)
  15784. {
  15785. if ((retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef)) ||
  15786. (retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumeratorTypeDef)))
  15787. {
  15788. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  15789. }
  15790. }
  15791. if (innerRetType == NULL)
  15792. {
  15793. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  15794. return;
  15795. }
  15796. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  15797. if (blockBody == NULL)
  15798. return;
  15799. }
  15800. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  15801. {
  15802. auto fieldType = markVal.mType;
  15803. auto fieldTypeInst = fieldType->ToTypeInstance();
  15804. if (fieldType == NULL)
  15805. return;
  15806. if (!markVal.mType->IsComposite())
  15807. markVal = LoadValue(markVal);
  15808. BfExprEvaluator exprEvaluator(this);
  15809. PopulateType(markVal.mType, BfPopulateType_Data);
  15810. if (markVal.mType->IsObjectOrInterface())
  15811. {
  15812. BfIRValue val = markVal.mValue;
  15813. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  15814. SizedArray<BfIRValue, 1> args;
  15815. args.push_back(val);
  15816. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  15817. }
  15818. else if (fieldType->IsSizedArray())
  15819. {
  15820. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)fieldType;
  15821. if (sizedArrayType->mElementType->WantsGCMarking())
  15822. {
  15823. BfTypedValue arrayValue = markVal;
  15824. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  15825. auto itr = CreateAlloca(intPtrType);
  15826. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  15827. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  15828. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  15829. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  15830. mBfIRBuilder->CreateBr(loopBB);
  15831. mBfIRBuilder->SetInsertPoint(loopBB);
  15832. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  15833. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  15834. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  15835. mBfIRBuilder->SetInsertPoint(bodyBB);
  15836. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  15837. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  15838. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  15839. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  15840. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  15841. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  15842. mBfIRBuilder->CreateStore(incValue, itr);
  15843. mBfIRBuilder->CreateBr(loopBB);
  15844. mBfIRBuilder->SetInsertPoint(doneBB);
  15845. }
  15846. }
  15847. else if ((fieldType->IsComposite()) && (!fieldType->IsTypedPrimitive()) && (fieldTypeInst != NULL))
  15848. {
  15849. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  15850. if (markMemberMethodInstance)
  15851. {
  15852. SizedArray<BfIRValue, 1> args;
  15853. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  15854. if (markVal.mType != methodOwner)
  15855. markVal = Cast(NULL, markVal, methodOwner);
  15856. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  15857. exprEvaluator.CreateCall(NULL, markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  15858. }
  15859. }
  15860. }
  15861. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  15862. {
  15863. Array<BfMethodInstance*> methodInstances;
  15864. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  15865. {
  15866. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  15867. auto chainedMethodInst = methodInstGroup.mDefault;
  15868. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  15869. {
  15870. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  15871. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  15872. {
  15873. methodInstances.push_back(chainedMethodInst);
  15874. }
  15875. }
  15876. }
  15877. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  15878. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  15879. {
  15880. bool isBetter;
  15881. bool isWorse;
  15882. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  15883. if (isBetter == isWorse)
  15884. {
  15885. return false;
  15886. }
  15887. return isWorse;
  15888. });
  15889. if (reverse)
  15890. std::reverse(methodInstances.begin(), methodInstances.end());
  15891. for (auto chainedMethodInst : methodInstances)
  15892. {
  15893. auto declModule = this;
  15894. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  15895. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  15896. BfExprEvaluator exprEvaluator(this);
  15897. SizedArray<BfIRValue, 1> args;
  15898. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  15899. exprEvaluator.CreateCall(NULL, moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  15900. }
  15901. }
  15902. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  15903. {
  15904. BF_ASSERT(mCurMethodInstance->mIsReified);
  15905. if (mCurTypeInstance->mHotTypeData == NULL)
  15906. {
  15907. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  15908. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  15909. }
  15910. auto hotMethod = mCurMethodInstance->mHotMethod;
  15911. for (auto depData : hotMethod->mReferences)
  15912. {
  15913. // Only virtual decls are allowed to already be there
  15914. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  15915. }
  15916. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  15917. int prevSize = (int)hotMethod->mReferences.size();
  15918. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  15919. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  15920. refCount++;
  15921. hotMethod->mReferences.Reserve(refCount);
  15922. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  15923. {
  15924. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  15925. hotThis->mRefCount++;
  15926. hotMethod->mReferences.Insert(0, hotThis);
  15927. prevSize++;
  15928. }
  15929. for (auto val : builder->mAllocatedData)
  15930. {
  15931. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  15932. hotMethod->mReferences.Add(hotAllocation);
  15933. }
  15934. for (auto val : builder->mUsedData)
  15935. hotMethod->mReferences.Add(val);
  15936. for (auto val : builder->mCalledMethods)
  15937. hotMethod->mReferences.Add(val);
  15938. for (auto val : builder->mDevirtualizedCalledMethods)
  15939. {
  15940. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  15941. hotMethod->mReferences.Add(devirtualizedMethod);
  15942. }
  15943. for (auto val : builder->mFunctionPtrs)
  15944. {
  15945. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  15946. hotMethod->mReferences.Add(funcRef);
  15947. }
  15948. for (auto val : builder->mInnerMethods)
  15949. {
  15950. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  15951. hotMethod->mReferences.Add(innerMethod);
  15952. }
  15953. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  15954. {
  15955. auto depData = hotMethod->mReferences[refIdx];
  15956. BF_ASSERT(depData != NULL);
  15957. depData->mRefCount++;
  15958. }
  15959. }
  15960. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  15961. {
  15962. auto methodDef = methodInstance->mMethodDef;
  15963. auto methodDeclaration = methodDef->mMethodDeclaration;
  15964. bool isThisStruct = false;
  15965. if (thisType != NULL)
  15966. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  15967. int argIdx = 0;
  15968. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  15969. argIdx++;
  15970. if (!methodDef->mIsStatic)
  15971. {
  15972. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15973. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15974. BfLocalVariable* paramVar = new BfLocalVariable();
  15975. paramVar->mResolvedType = thisType;
  15976. paramVar->mName = "this";
  15977. if (!thisType->IsValuelessType())
  15978. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  15979. else
  15980. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  15981. if ((!mIsComptimeModule) && (thisType->IsSplattable()) && (methodInstance->AllowsSplatting(-1)))
  15982. {
  15983. if (!thisType->IsTypedPrimitive())
  15984. paramVar->mIsSplat = true;
  15985. }
  15986. else if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  15987. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  15988. auto thisTypeInst = thisType->ToTypeInstance();
  15989. paramVar->mIsStruct = isThisStruct;
  15990. paramVar->mAddr = BfIRValue();
  15991. paramVar->mIsThis = true;
  15992. paramVar->mParamIdx = -1;
  15993. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  15994. {
  15995. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  15996. }
  15997. else
  15998. {
  15999. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16000. }
  16001. paramVar->mReadFromId = -1;
  16002. paramVar->Init();
  16003. if (methodDeclaration == NULL)
  16004. UseDefaultSrcPos();
  16005. AddLocalVariableDef(paramVar);
  16006. if (!thisType->IsValuelessType())
  16007. {
  16008. if (wantsDIData)
  16009. {
  16010. BfType* thisPtrType = thisType;
  16011. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  16012. if (!thisType->IsValueType())
  16013. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  16014. else if (!paramVar->mIsSplat)
  16015. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  16016. diParams->push_back(diType);
  16017. }
  16018. if (paramVar->mIsSplat)
  16019. {
  16020. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16021. }
  16022. else
  16023. {
  16024. argIdx++;
  16025. if (loweredTypeCode2 != BfTypeCode_None)
  16026. argIdx++;
  16027. }
  16028. }
  16029. }
  16030. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16031. argIdx++;
  16032. bool hadParams = false;
  16033. bool hasDefault = false;
  16034. int compositeVariableIdx = -1;
  16035. int paramIdx = 0;
  16036. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16037. {
  16038. // We already issues a type error for this param if we had one in declaration processing
  16039. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  16040. BfLocalVariable* paramVar = new BfLocalVariable();
  16041. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16042. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16043. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  16044. auto resolvedType = methodInstance->GetParamType(paramIdx);
  16045. if (resolvedType == NULL)
  16046. {
  16047. AssertErrorState();
  16048. paramVar->mParamFailed = true;
  16049. }
  16050. prevIgnoreErrors.Restore();
  16051. PopulateType(resolvedType, BfPopulateType_Declaration);
  16052. paramVar->mResolvedType = resolvedType;
  16053. int namePrefixCount = 0;
  16054. paramVar->mName = methodInstance->GetParamName(paramIdx, namePrefixCount);
  16055. paramVar->mNamePrefixCount = (uint8)namePrefixCount;
  16056. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  16057. if (!isParamSkipped)
  16058. {
  16059. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16060. if (resolvedType->IsMethodRef())
  16061. {
  16062. paramVar->mIsSplat = true;
  16063. }
  16064. else if ((!mIsComptimeModule) && (resolvedType->IsComposite()) && (resolvedType->IsSplattable()))
  16065. {
  16066. if (methodInstance->AllowsSplatting(paramIdx))
  16067. {
  16068. auto resolveTypeInst = resolvedType->ToTypeInstance();
  16069. if ((resolveTypeInst != NULL) && (resolveTypeInst->mIsCRepr))
  16070. paramVar->mIsSplat = true;
  16071. else
  16072. {
  16073. int splatCount = resolvedType->GetSplatCount();
  16074. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16075. paramVar->mIsSplat = true;
  16076. }
  16077. }
  16078. }
  16079. }
  16080. else
  16081. {
  16082. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  16083. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  16084. }
  16085. paramVar->mIsLowered = (!mIsComptimeModule) && resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  16086. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  16087. paramVar->mParamIdx = paramIdx;
  16088. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  16089. paramVar->mReadFromId = 0;
  16090. if (resolvedType->IsRef())
  16091. {
  16092. auto refType = (BfRefType*)resolvedType;
  16093. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  16094. if (refType->mRefKind == BfRefType::RefKind_In)
  16095. {
  16096. paramVar->mIsReadOnly = true;
  16097. }
  16098. }
  16099. else
  16100. {
  16101. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16102. if (methodDef->mMethodType != BfMethodType_Mixin)
  16103. paramVar->mIsReadOnly = true;
  16104. }
  16105. if (paramVar->mResolvedType->IsGenericParam())
  16106. {
  16107. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  16108. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  16109. {
  16110. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  16111. paramVar->mResolvedType = typedVal.mType;
  16112. paramVar->mConstValue = typedVal.mValue;
  16113. }
  16114. }
  16115. if (paramVar->mResolvedType->IsConstExprValue())
  16116. {
  16117. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  16118. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  16119. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  16120. BF_ASSERT(unspecParamType->IsGenericParam());
  16121. if (unspecParamType->IsGenericParam())
  16122. {
  16123. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  16124. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  16125. {
  16126. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  16127. if (genericParamInst->mTypeConstraint != NULL)
  16128. {
  16129. BfExprEvaluator exprEvaluator(this);
  16130. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  16131. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  16132. auto checkType = genericParamInst->mTypeConstraint;
  16133. if (checkType->IsTypedPrimitive())
  16134. checkType = checkType->GetUnderlyingType();
  16135. if (exprEvaluator.mResult.mType == checkType)
  16136. {
  16137. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  16138. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  16139. BF_ASSERT(paramVar->mConstValue.IsConst());
  16140. }
  16141. else
  16142. {
  16143. AssertErrorState();
  16144. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  16145. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  16146. }
  16147. }
  16148. }
  16149. }
  16150. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  16151. if (paramVar->mResolvedType->IsConstExprValue())
  16152. {
  16153. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  16154. //AssertErrorState();
  16155. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  16156. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  16157. }
  16158. }
  16159. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  16160. {
  16161. if (compositeVariableIdx == -1)
  16162. {
  16163. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  16164. BfLocalVariable* localVar = new BfLocalVariable();
  16165. auto paramInst = &methodInstance->mParams[paramIdx];
  16166. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  16167. localVar->mName = paramDef->mName;
  16168. localVar->mNamePrefixCount = paramDef->mNamePrefixCount;
  16169. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  16170. localVar->mCompositeCount = 0;
  16171. DoAddLocalVariable(localVar);
  16172. }
  16173. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  16174. }
  16175. if (!mCurTypeInstance->IsDelegateOrFunction())
  16176. CheckVariableDef(paramVar);
  16177. paramVar->Init();
  16178. AddLocalVariableDef(paramVar);
  16179. if (!isParamSkipped)
  16180. {
  16181. if (wantsDIData)
  16182. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  16183. if (paramVar->mIsSplat)
  16184. {
  16185. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16186. }
  16187. else
  16188. {
  16189. argIdx++;
  16190. }
  16191. if (loweredTypeCode2 != BfTypeCode_None)
  16192. argIdx++;
  16193. }
  16194. }
  16195. // Try to find an ending delegate params composite
  16196. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  16197. {
  16198. auto paramDef = methodDef->mParams.back();
  16199. if (paramDef->mParamKind == BfParamKind_Params)
  16200. {
  16201. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  16202. if (paramsType == NULL)
  16203. {
  16204. AssertErrorState();
  16205. }
  16206. else if (paramsType->IsGenericParam())
  16207. {
  16208. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  16209. if (genericParamInstance->mTypeConstraint != NULL)
  16210. {
  16211. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16212. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16213. ((typeInstConstraint != NULL) &&
  16214. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  16215. {
  16216. BfLocalVariable* localVar = new BfLocalVariable();
  16217. localVar->mName = paramDef->mName;
  16218. localVar->mResolvedType = paramsType;
  16219. localVar->mCompositeCount = 0;
  16220. DoAddLocalVariable(localVar);
  16221. }
  16222. }
  16223. }
  16224. else if (paramsType->IsDelegate())
  16225. {
  16226. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  16227. if (invokeMethodInstance != NULL)
  16228. {
  16229. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  16230. // and wasn't cleared by the preceding loop
  16231. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  16232. BfLocalVariable* localVar = new BfLocalVariable();
  16233. localVar->mName = paramDef->mName;
  16234. localVar->mResolvedType = paramsType;
  16235. localVar->mCompositeCount = 0;
  16236. DoAddLocalVariable(localVar);
  16237. }
  16238. }
  16239. }
  16240. }
  16241. }
  16242. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  16243. {
  16244. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  16245. // return;
  16246. auto startMethodState = mCurMethodState;
  16247. auto _ClearState = [&]()
  16248. {
  16249. mCurMethodState->mLocalMethods.Clear();
  16250. for (auto& local : mCurMethodState->mLocals)
  16251. delete local;
  16252. mCurMethodState->mLocals.Clear();
  16253. mCurMethodState->mLocalVarSet.Clear();
  16254. };
  16255. while (true)
  16256. {
  16257. bool didWork = false;
  16258. // 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
  16259. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  16260. // however (compiler bug), so this is the safest way
  16261. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  16262. {
  16263. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  16264. {
  16265. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  16266. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  16267. if (!mHadBuildError)
  16268. {
  16269. // Process as a closure - that allows us to look back and see the const locals and stuff
  16270. BfClosureState closureState;
  16271. mCurMethodState->mClosureState = &closureState;
  16272. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  16273. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  16274. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  16275. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  16276. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  16277. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  16278. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  16279. _ClearState();
  16280. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  16281. {
  16282. auto localVar = new BfLocalVariable();
  16283. *localVar = constLocal;
  16284. DoAddLocalVariable(localVar);
  16285. }
  16286. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  16287. bool doProcess = !mCompiler->mCanceling;
  16288. if (doProcess)
  16289. {
  16290. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  16291. ProcessMethod(deferredLocalMethod->mMethodInstance);
  16292. }
  16293. }
  16294. delete deferredLocalMethod;
  16295. mContext->CheckLockYield();
  16296. didWork = true;
  16297. }
  16298. mCurMethodState->mDeferredLocalMethods.Clear();
  16299. }
  16300. for (auto& kv : mCurMethodState->mLocalMethodCache)
  16301. {
  16302. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  16303. }
  16304. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  16305. {
  16306. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  16307. {
  16308. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  16309. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  16310. BfClosureState closureState;
  16311. mCurMethodState->mClosureState = &closureState;
  16312. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  16313. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  16314. if (lambdaInstance->mClosureTypeInstance != NULL)
  16315. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  16316. else
  16317. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  16318. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  16319. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  16320. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  16321. _ClearState();
  16322. for (auto& constLocal : lambdaInstance->mConstLocals)
  16323. {
  16324. //if (constLocal.mIsThis)
  16325. {
  16326. // Valueless 'this'
  16327. closureState.mConstLocals.Add(constLocal);
  16328. }
  16329. /*else
  16330. {
  16331. auto localVar = new BfLocalVariable();
  16332. *localVar = constLocal;
  16333. DoAddLocalVariable(localVar);
  16334. }*/
  16335. }
  16336. BfMethodInstanceGroup methodInstanceGroup;
  16337. methodInstanceGroup.mOwner = mCurTypeInstance;
  16338. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  16339. bool doProcess = !mCompiler->mCanceling;
  16340. if (doProcess)
  16341. {
  16342. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  16343. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  16344. ProcessMethod(lambdaInstance->mMethodInstance);
  16345. lambdaInstance->mMethodInstance->mMethodInstanceGroup = NULL;
  16346. if (lambdaInstance->mDtorMethodInstance != NULL)
  16347. {
  16348. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  16349. auto startMethodState2 = mCurMethodState;
  16350. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  16351. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = NULL;
  16352. }
  16353. }
  16354. didWork = true;
  16355. }
  16356. mContext->CheckLockYield();
  16357. mCurMethodState->mDeferredLambdaInstances.Clear();
  16358. }
  16359. if (!didWork)
  16360. break;
  16361. }
  16362. }
  16363. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  16364. {
  16365. if (checkType->IsComposite())
  16366. PopulateType(checkType, BfPopulateType_Data);
  16367. if (!checkType->WantsGCMarking())
  16368. return;
  16369. auto typeInstance = checkType->ToTypeInstance();
  16370. bool callMarkMethod = false;
  16371. // Call the actual marking method
  16372. if (memberDepth == 0)
  16373. {
  16374. // Don't call marking method on self
  16375. }
  16376. else if (checkType->IsObjectOrInterface())
  16377. {
  16378. if (!objectOffsets.Add(curOffset))
  16379. {
  16380. return;
  16381. }
  16382. callMarkMethod = true;
  16383. }
  16384. else if (checkType->IsSizedArray())
  16385. {
  16386. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  16387. if (sizedArrayType->mElementType->WantsGCMarking())
  16388. {
  16389. BfTypedValue arrayValue = thisValue;
  16390. if (thisValue.mType != checkType)
  16391. {
  16392. BfIRValue srcValue = thisValue.mValue;
  16393. if (curOffset != 0)
  16394. {
  16395. if (!thisValue.mType->IsPointer())
  16396. {
  16397. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  16398. auto int8PtrType = CreatePointerType(int8Type);
  16399. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  16400. }
  16401. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  16402. }
  16403. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  16404. }
  16405. if (sizedArrayType->mElementCount > 6)
  16406. {
  16407. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  16408. auto itr = CreateAlloca(intPtrType);
  16409. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  16410. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  16411. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  16412. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  16413. mBfIRBuilder->CreateBr(loopBB);
  16414. mBfIRBuilder->SetInsertPoint(loopBB);
  16415. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  16416. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  16417. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  16418. mBfIRBuilder->SetInsertPoint(bodyBB);
  16419. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16420. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16421. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  16422. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16423. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16424. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  16425. mBfIRBuilder->CreateStore(incValue, itr);
  16426. mBfIRBuilder->CreateBr(loopBB);
  16427. mBfIRBuilder->SetInsertPoint(doneBB);
  16428. }
  16429. else
  16430. {
  16431. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  16432. {
  16433. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16434. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16435. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  16436. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16437. HashSet<int> objectOffsets;
  16438. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16439. }
  16440. }
  16441. }
  16442. }
  16443. else if (typeInstance != NULL)
  16444. {
  16445. typeInstance->mTypeDef->PopulateMemberSets();
  16446. BfMemberSetEntry* entry = NULL;
  16447. BfMethodDef* methodDef = NULL;
  16448. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  16449. {
  16450. methodDef = (BfMethodDef*)entry->mMemberDef;
  16451. if (methodDef->HasBody())
  16452. {
  16453. callMarkMethod = true;
  16454. }
  16455. }
  16456. }
  16457. if (callMarkMethod)
  16458. {
  16459. BfTypedValue markValue;
  16460. auto memberType = checkType;
  16461. if (memberType->IsObjectOrInterface())
  16462. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  16463. auto memberPtrType = CreatePointerType(memberType);
  16464. if (curOffset == 0)
  16465. {
  16466. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  16467. }
  16468. else
  16469. {
  16470. if (!thisValue.mType->IsPointer())
  16471. {
  16472. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  16473. auto int8PtrType = CreatePointerType(int8Type);
  16474. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  16475. }
  16476. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  16477. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  16478. }
  16479. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  16480. return;
  16481. }
  16482. auto methodDef = mCurMethodInstance->mMethodDef;
  16483. if (checkType->IsPayloadEnum())
  16484. {
  16485. for (auto& fieldInst : typeInstance->mFieldInstances)
  16486. {
  16487. if (!fieldInst.mIsEnumPayloadCase)
  16488. continue;
  16489. auto fieldDef = fieldInst.GetFieldDef();
  16490. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  16491. }
  16492. return;
  16493. }
  16494. if (typeInstance == NULL)
  16495. return;
  16496. for (auto& fieldInst : typeInstance->mFieldInstances)
  16497. {
  16498. auto fieldDef = fieldInst.GetFieldDef();
  16499. if (fieldDef == NULL)
  16500. continue;
  16501. if (fieldDef->mIsStatic)
  16502. continue;
  16503. if (typeInstance == mCurTypeInstance)
  16504. {
  16505. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  16506. // we may be marking member values that can never contain a value anyway, but this is benign
  16507. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16508. continue;
  16509. }
  16510. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  16511. }
  16512. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  16513. {
  16514. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  16515. }
  16516. }
  16517. void BfModule::EmitGCMarkMembers()
  16518. {
  16519. auto methodDef = mCurMethodInstance->mMethodDef;
  16520. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  16521. BfModuleMethodInstance markFromGCThreadMethodInstance;
  16522. if (gcType != NULL)
  16523. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  16524. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  16525. {
  16526. if (mCurTypeInstance->IsBoxed())
  16527. {
  16528. // This already gets filled in by the normal boxed forwarding
  16529. }
  16530. else
  16531. {
  16532. auto thisValue = GetThis();
  16533. if (thisValue.IsSplat())
  16534. {
  16535. BfIRFunction func = mCurMethodInstance->mIRFunction;
  16536. int argIdx = 0;
  16537. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  16538. {
  16539. if (checkType->IsStruct())
  16540. {
  16541. auto checkTypeInstance = checkType->ToTypeInstance();
  16542. if (checkTypeInstance->mBaseType != NULL)
  16543. checkTypeLambda(checkTypeInstance->mBaseType);
  16544. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  16545. {
  16546. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  16547. if (fieldInstance->mDataIdx >= 0)
  16548. checkTypeLambda(fieldInstance->GetResolvedType());
  16549. }
  16550. }
  16551. else if (checkType->IsMethodRef())
  16552. {
  16553. BFMODULE_FATAL(this, "Not handled");
  16554. }
  16555. else if (checkType->WantsGCMarking())
  16556. {
  16557. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  16558. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  16559. argIdx++;
  16560. }
  16561. };
  16562. checkTypeLambda(thisValue.mType);
  16563. }
  16564. else if (!methodDef->mIsStatic)
  16565. {
  16566. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  16567. {
  16568. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  16569. if (moduleMethodInst)
  16570. {
  16571. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  16572. bool wantsBaseMarking = true;
  16573. if (methodBaseType == mContext->mBfObjectType)
  16574. {
  16575. wantsBaseMarking = false;
  16576. PopulateType(methodBaseType);
  16577. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  16578. {
  16579. if ((fieldInstance.GetFieldDef()->mDeclaringType->IsExtension()) &&
  16580. (fieldInstance.mResolvedType->WantsGCMarking()))
  16581. wantsBaseMarking = true;
  16582. }
  16583. }
  16584. if (wantsBaseMarking)
  16585. {
  16586. auto thisValue = GetThis();
  16587. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  16588. SizedArray<BfIRValue, 1> args;
  16589. if ((!mIsComptimeModule) && (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1)))
  16590. {
  16591. BfExprEvaluator exprEvaluator(this);
  16592. exprEvaluator.SplatArgs(baseValue, args);
  16593. }
  16594. else
  16595. {
  16596. args.push_back(baseValue.mValue);
  16597. }
  16598. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  16599. }
  16600. }
  16601. }
  16602. }
  16603. if (!methodDef->mIsStatic)
  16604. {
  16605. HashSet<int> objectOffsets;
  16606. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  16607. }
  16608. else
  16609. {
  16610. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  16611. {
  16612. if (thisValue.IsSplat())
  16613. break;
  16614. auto fieldDef = fieldInst.GetFieldDef();
  16615. if (fieldDef == NULL)
  16616. continue;
  16617. if (fieldInst.mIsThreadLocal)
  16618. continue;
  16619. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  16620. {
  16621. // For extensions, only handle these fields in the appropriate extension
  16622. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16623. continue;
  16624. if (!fieldInst.mFieldIncluded)
  16625. continue;
  16626. auto fieldType = fieldInst.mResolvedType;
  16627. auto fieldDef = fieldInst.GetFieldDef();
  16628. BfTypedValue markVal;
  16629. if (fieldDef->mIsConst)
  16630. continue;
  16631. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  16632. continue;
  16633. mBfIRBuilder->PopulateType(fieldType);
  16634. if (fieldType->IsValuelessType())
  16635. continue;
  16636. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  16637. {
  16638. StringT<128> staticVarName;
  16639. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  16640. if (staticVarName.StartsWith('#'))
  16641. continue;
  16642. markVal = ReferenceStaticField(&fieldInst);
  16643. }
  16644. else if (!fieldDef->mIsStatic)
  16645. {
  16646. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  16647. }
  16648. if (markVal)
  16649. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  16650. }
  16651. }
  16652. }
  16653. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  16654. CallChainedMethods(mCurMethodInstance, false);
  16655. }
  16656. }
  16657. }
  16658. void BfModule::EmitGCFindTLSMembers()
  16659. {
  16660. auto methodDef = mCurMethodInstance->mMethodDef;
  16661. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  16662. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  16663. BF_ASSERT(reportTLSMark);
  16664. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  16665. {
  16666. auto fieldDef = fieldInst.GetFieldDef();
  16667. if (fieldDef == NULL)
  16668. continue;
  16669. if (!fieldInst.mIsThreadLocal)
  16670. continue;
  16671. // For extensions, only handle these fields in the appropriate extension
  16672. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16673. continue;
  16674. if (!fieldInst.mFieldIncluded)
  16675. continue;
  16676. if (fieldDef->mIsConst)
  16677. continue;
  16678. auto fieldType = fieldInst.mResolvedType;
  16679. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  16680. continue;
  16681. if (fieldType->IsValuelessType())
  16682. continue;
  16683. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  16684. if (markVal)
  16685. {
  16686. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  16687. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  16688. SizedArray<BfIRValue, 2> llvmArgs;
  16689. llvmArgs.push_back(fieldRefPtr);
  16690. llvmArgs.push_back(markFuncPtr);
  16691. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  16692. }
  16693. }
  16694. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  16695. CallChainedMethods(mCurMethodInstance, false);
  16696. }
  16697. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup, bool forceIRWrites)
  16698. {
  16699. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  16700. if (mIsComptimeModule)
  16701. {
  16702. BF_ASSERT(!mCompiler->IsAutocomplete());
  16703. }
  16704. if (mAwaitingInitFinish)
  16705. FinishInit();
  16706. if (!methodInstance->mIsReified)
  16707. BF_ASSERT(!mIsReified);
  16708. BF_ASSERT((!methodInstance->GetOwner()->IsUnspecializedTypeVariation()) || (mIsComptimeModule));
  16709. if (methodInstance->mMethodInfoEx != NULL)
  16710. {
  16711. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  16712. {
  16713. if (methodGenericArg->IsMethodRef())
  16714. {
  16715. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  16716. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  16717. }
  16718. }
  16719. }
  16720. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, (mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized) && (!forceIRWrites));
  16721. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  16722. {
  16723. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  16724. }
  16725. SetAndRestoreValue<bool> prevIsClassifying;
  16726. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  16727. (mCompiler->mResolvePassData != NULL))
  16728. {
  16729. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  16730. prevIsClassifying.Init(mCompiler->mResolvePassData->mIsClassifying, false);
  16731. }
  16732. if (methodInstance->mHasBeenProcessed)
  16733. {
  16734. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  16735. return;
  16736. }
  16737. if (methodInstance->mFailedConstraints)
  16738. {
  16739. // The only way this should be able to happen is if we fail our generic param check
  16740. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  16741. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  16742. methodInstance->mHasBeenProcessed = true;
  16743. return;
  16744. }
  16745. if (HasExecutedOutput())
  16746. {
  16747. BF_ASSERT(mIsModuleMutable);
  16748. }
  16749. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  16750. if (!mIsComptimeModule)
  16751. {
  16752. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  16753. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  16754. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  16755. {
  16756. auto owningModule = methodInstance->GetOwner()->mModule;
  16757. if (owningModule->mIsScratchModule)
  16758. {
  16759. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  16760. }
  16761. else
  16762. {
  16763. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  16764. if (owningModule->mOnDemandMethodCount > 0)
  16765. owningModule->mOnDemandMethodCount--;
  16766. }
  16767. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  16768. VerifyOnDemandMethods();
  16769. }
  16770. }
  16771. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  16772. // self-referencing append allocations in ctor@calcAppend
  16773. methodInstance->mHasBeenProcessed = true;
  16774. mIncompleteMethodCount--;
  16775. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  16776. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  16777. auto methodDef = methodInstance->mMethodDef;
  16778. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16779. if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  16780. mBfIRBuilder->mIgnoreWrites = true;
  16781. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  16782. {
  16783. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  16784. // so we get the new vdata for it
  16785. methodInstance->GetOwner()->mDirty = true;
  16786. }
  16787. int dependentGenericStartIdx = 0;
  16788. if ((methodDef->mIsLocalMethod) && (mCurMethodState != NULL)) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  16789. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  16790. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  16791. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  16792. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  16793. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  16794. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  16795. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors);
  16796. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, mIsComptimeModule);
  16797. if ((methodInstance->mIsReified) &&
  16798. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  16799. {
  16800. mCurTypeInstance->mHasBeenInstantiated = true;
  16801. }
  16802. // Warnings are shown in the capture phase
  16803. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  16804. mIgnoreWarnings = true;
  16805. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  16806. UseDefaultSrcPos();
  16807. if ((mIsComptimeModule) && (methodDef->mIsStatic))
  16808. {
  16809. PopulateType(mCurTypeInstance, BfPopulateType_AllowStaticMethods);
  16810. }
  16811. else
  16812. {
  16813. // We may not actually be populated in relatively rare autocompelte cases
  16814. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  16815. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  16816. }
  16817. BfAstNode* nameNode = NULL;
  16818. if (methodDeclaration != NULL)
  16819. {
  16820. nameNode = methodDeclaration->mNameNode;
  16821. if (nameNode == NULL)
  16822. {
  16823. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  16824. nameNode = ctorDeclaration->mThisToken;
  16825. }
  16826. }
  16827. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  16828. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) &&
  16829. (methodDef->mIdx >= 0) && (!methodInstance->mIsForeignMethodDef))
  16830. {
  16831. if (methodInstance->GetExplicitInterface() == NULL)
  16832. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  16833. else
  16834. {
  16835. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  16836. {
  16837. auto ifaceInst = ifaceEntry.mInterfaceType;
  16838. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  16839. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  16840. if (methodInstance->GetExplicitInterface() != ifaceInst)
  16841. continue;
  16842. ifaceInst->mTypeDef->PopulateMemberSets();
  16843. BfMethodDef* nextMethod = NULL;
  16844. BfMemberSetEntry* entry = NULL;
  16845. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16846. nextMethod = (BfMethodDef*)entry->mMemberDef;
  16847. while (nextMethod != NULL)
  16848. {
  16849. auto checkMethod = nextMethod;
  16850. nextMethod = nextMethod->mNextWithSameName;
  16851. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  16852. if (implMethodInst == methodInstance)
  16853. {
  16854. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  16855. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  16856. }
  16857. }
  16858. }
  16859. }
  16860. if (methodDef->mIsOverride)
  16861. {
  16862. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  16863. {
  16864. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  16865. if (ventry.mDeclaringMethod.mMethodNum == -1)
  16866. continue;
  16867. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  16868. if (virtMethod != NULL)
  16869. {
  16870. if (virtMethod == methodInstance)
  16871. {
  16872. // Is matching method
  16873. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  16874. {
  16875. auto baseType = mCurTypeInstance->mBaseType;
  16876. if (baseType != NULL)
  16877. {
  16878. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  16879. baseType = baseType->mBaseType;
  16880. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  16881. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  16882. }
  16883. }
  16884. break;
  16885. }
  16886. }
  16887. }
  16888. }
  16889. }
  16890. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d Incomplete:%d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified, mIncompleteMethodCount);
  16891. int importStrNum = -1;
  16892. auto importKind = methodInstance->GetImportKind();
  16893. if ((!mCompiler->mIsResolveOnly) &&
  16894. ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic)))
  16895. {
  16896. if (auto customAttr = methodInstance->GetCustomAttributes()->Get(mCompiler->mImportAttributeTypeDef))
  16897. {
  16898. if (customAttr->mCtorArgs.size() == 1)
  16899. {
  16900. auto fileNameArg = customAttr->mCtorArgs[0];
  16901. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  16902. if (constant != NULL)
  16903. {
  16904. if (!constant->IsNull())
  16905. importStrNum = constant->mInt32;
  16906. }
  16907. else
  16908. {
  16909. importStrNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  16910. }
  16911. if (importStrNum != -1)
  16912. {
  16913. if (!mStringPoolRefs.Contains(importStrNum))
  16914. mStringPoolRefs.Add(importStrNum);
  16915. }
  16916. }
  16917. }
  16918. }
  16919. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  16920. {
  16921. if (mBfIRBuilder->mIgnoreWrites)
  16922. return;
  16923. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  16924. if (!methodInstance->mIRFunction)
  16925. {
  16926. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  16927. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  16928. BF_ASSERT(dllImportGlobalVar || methodInstance->mHasFailed);
  16929. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  16930. }
  16931. if (HasCompiledOutput())
  16932. {
  16933. BfDllImportEntry dllImportEntry;
  16934. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  16935. dllImportEntry.mMethodInstance = mCurMethodInstance;
  16936. mDllImportEntries.push_back(dllImportEntry);
  16937. }
  16938. return;
  16939. }
  16940. StringT<128> mangledName;
  16941. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16942. if (!methodInstance->mIRFunction)
  16943. {
  16944. bool isIntrinsic = false;
  16945. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  16946. }
  16947. if (methodInstance->mIsIntrinsic)
  16948. return;
  16949. if (mCurTypeInstance->IsFunction())
  16950. return;
  16951. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  16952. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  16953. if (methodDef->mBody != NULL)
  16954. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  16955. else if (methodDeclaration != NULL)
  16956. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  16957. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  16958. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  16959. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  16960. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  16961. if ((mCurMethodState == NULL) && (!IsInSpecializedSection())) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  16962. {
  16963. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()))
  16964. {
  16965. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(methodDef->mBody))
  16966. sourceClassifier->VisitChildNoRef(methodDef->mBody);
  16967. }
  16968. }
  16969. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  16970. BfMethodState methodState;
  16971. if (mCurMethodState != NULL)
  16972. methodState.mClosureState = mCurMethodState->mClosureState;
  16973. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  16974. {
  16975. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  16976. if (methodInstance->mHotMethod == NULL)
  16977. CheckHotMethod(methodInstance, mangledName);
  16978. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  16979. }
  16980. methodState.mPrevMethodState = mCurMethodState;
  16981. methodState.mMethodInstance = methodInstance;
  16982. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16983. if (methodInstance->GetCustomAttributes() != NULL)
  16984. {
  16985. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  16986. if (typeOptionsIdx != -1)
  16987. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  16988. }
  16989. BfTypeState typeState(mCurTypeInstance);
  16990. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  16991. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  16992. BfMethodInstance* unspecializedMethodInstance = NULL;
  16993. if ((prevMethodState.mPrevVal != NULL) &&
  16994. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  16995. {
  16996. // This is 'inner' (probably a closure) - use binding from outer function
  16997. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  16998. }
  16999. else if ((methodInstance->mIsUnspecialized) ||
  17000. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  17001. {
  17002. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17003. }
  17004. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  17005. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation || mIsComptimeModule) && (!methodInstance->mMethodDef->mIsLocalMethod) && (!methodInstance->mMethodDef->mDeclaringType->IsEmitted()))))
  17006. {
  17007. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  17008. if ((mIsComptimeModule) && (!unspecializedMethodInstance->mHasBeenProcessed))
  17009. {
  17010. // This will have already been populated by CeMachine
  17011. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17012. }
  17013. else
  17014. {
  17015. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  17016. if (!unspecializedMethodInstance->mHasBeenProcessed)
  17017. {
  17018. // Make sure the unspecialized method is processed so we can take its bindings
  17019. // Clear mCurMethodState so we don't think we're in a local method
  17020. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  17021. if (unspecializedMethodInstance->mMethodProcessRequest == NULL)
  17022. unspecializedMethodInstance->mDeclModule->mIncompleteMethodCount++;
  17023. mContext->ProcessMethod(unspecializedMethodInstance);
  17024. }
  17025. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17026. }
  17027. }
  17028. if (methodDef->mMethodType == BfMethodType_Operator)
  17029. {
  17030. auto operatorDef = (BfOperatorDef*) methodDef;
  17031. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  17032. auto paramErrorRefNode = refNode;
  17033. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  17034. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  17035. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  17036. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  17037. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  17038. {
  17039. if (methodDef->mParams.size() != 2)
  17040. {
  17041. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  17042. }
  17043. else
  17044. {
  17045. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17046. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17047. checkParam0 = checkParam0->GetUnderlyingType();
  17048. auto checkParam1 = mCurMethodInstance->GetParamType(1);
  17049. if ((checkParam1->IsRef()) && (!checkParam1->IsOut()))
  17050. checkParam1 = checkParam1->GetUnderlyingType();
  17051. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  17052. (checkParam1 != mCurTypeInstance) && (!checkParam1->IsSelf()))
  17053. {
  17054. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  17055. }
  17056. }
  17057. BfType* wantType = NULL;
  17058. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  17059. {
  17060. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  17061. }
  17062. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  17063. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  17064. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  17065. }
  17066. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  17067. {
  17068. if (methodDef->mIsStatic)
  17069. {
  17070. if (methodDef->mParams.size() != 1)
  17071. {
  17072. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  17073. }
  17074. else
  17075. {
  17076. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17077. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17078. checkParam0 = checkParam0->GetUnderlyingType();
  17079. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()))
  17080. {
  17081. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  17082. }
  17083. }
  17084. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  17085. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  17086. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  17087. {
  17088. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  17089. }
  17090. }
  17091. else
  17092. {
  17093. if (methodDef->mParams.size() != 0)
  17094. {
  17095. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  17096. }
  17097. if (!mCurMethodInstance->mReturnType->IsVoid())
  17098. {
  17099. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  17100. }
  17101. }
  17102. }
  17103. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  17104. {
  17105. if (methodDef->mParams.size() != 1)
  17106. {
  17107. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  17108. }
  17109. if (!mCurMethodInstance->mReturnType->IsVoid())
  17110. {
  17111. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  17112. }
  17113. }
  17114. else // Conversion
  17115. {
  17116. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  17117. {
  17118. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  17119. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  17120. }
  17121. if (methodDef->mParams.size() != 1)
  17122. {
  17123. auto refNode = paramErrorRefNode;
  17124. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  17125. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  17126. Fail("Conversion operators must declare one parameter", refNode);
  17127. }
  17128. else if ((methodInstance->mMethodInfoEx == NULL) ||
  17129. (methodInstance->mMethodInfoEx->mMethodGenericArguments.IsEmpty()) ||
  17130. ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation)))
  17131. {
  17132. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17133. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17134. checkParam0 = checkParam0->GetUnderlyingType();
  17135. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  17136. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  17137. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  17138. if (checkParam0 == mCurMethodInstance->mReturnType)
  17139. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  17140. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  17141. // happened here
  17142. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (checkParam0 != mContext->mBfObjectType)))
  17143. {
  17144. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  17145. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, checkParam0->ToTypeInstance());
  17146. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  17147. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  17148. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  17149. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  17150. }
  17151. }
  17152. }
  17153. }
  17154. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mBfIRBuilder->mIgnoreWrites) && (mHasFullDebugInfo);
  17155. if (methodDef->mMethodType == BfMethodType_Mixin)
  17156. wantsDIData = false;
  17157. if (mCurTypeInstance->IsUnspecializedType())
  17158. wantsDIData = false;
  17159. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  17160. wantsDIData = false;
  17161. bool wantsDIVariables = wantsDIData;
  17162. if (methodDef->mIsExtern)
  17163. wantsDIVariables = false;
  17164. SizedArray<BfIRMDNode, 8> diParams;
  17165. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  17166. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  17167. BfType* thisType = NULL;
  17168. if (!methodDef->mIsStatic)
  17169. {
  17170. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  17171. thisType = methodState.mClosureState->mClosureType;
  17172. else
  17173. thisType = mCurTypeInstance;
  17174. }
  17175. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  17176. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  17177. //////////////////////////////////////////////////////////////////////////
  17178. //
  17179. {
  17180. if (methodDeclaration != NULL)
  17181. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17182. else if (methodDef->mBody != NULL)
  17183. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17184. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17185. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  17186. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17187. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17188. }
  17189. BfIRMDNode diFunction;
  17190. if (wantsDIData)
  17191. {
  17192. BP_ZONE("BfModule::DoMethodDeclaration.DISetup");
  17193. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  17194. int defLine = mCurFilePosition.mCurLine;
  17195. if (mDICompileUnit)
  17196. {
  17197. int flags = 0;
  17198. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  17199. if (methodDef->mProtection == BfProtection_Public)
  17200. flags = llvm::DINode::FlagPublic;
  17201. else if (methodDef->mProtection == BfProtection_Protected)
  17202. flags = llvm::DINode::FlagProtected;
  17203. else
  17204. flags = llvm::DINode::FlagPrivate;
  17205. if (methodDef->mIsOverride)
  17206. {
  17207. //flags |= llvm::DINode::FlagVirtual;
  17208. }
  17209. else if (methodDef->mIsVirtual)
  17210. flags |= llvm::DINode::FlagIntroducedVirtual;
  17211. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  17212. flags |= llvm::DINode::FlagStaticMember;
  17213. else
  17214. {
  17215. if ((mCurTypeInstance->IsValuelessType()) ||
  17216. ((!mIsComptimeModule) && (mCurTypeInstance->IsSplattable())))
  17217. flags |= llvm::DINode::FlagStaticMember;
  17218. }
  17219. flags |= llvm::DINode::FlagPrototyped;
  17220. if (methodDef->mMethodType == BfMethodType_Ctor)
  17221. {
  17222. flags |= llvm::DINode::FlagArtificial;
  17223. }
  17224. auto llvmFunction = methodInstance->mIRFunction;
  17225. SizedArray<BfIRMDNode, 1> genericArgs;
  17226. SizedArray<BfIRValue, 1> genericConstValueArgs;
  17227. String methodName;
  17228. if (methodInstance->GetForeignType() != NULL)
  17229. {
  17230. methodName += TypeToString(methodInstance->GetForeignType());
  17231. methodName += ".";
  17232. }
  17233. if (methodInstance->GetExplicitInterface() != NULL)
  17234. {
  17235. methodName += TypeToString(methodInstance->GetExplicitInterface());
  17236. methodName += ".";
  17237. }
  17238. methodName += methodDef->mName;
  17239. if (methodInstance->GetNumGenericArguments() != 0)
  17240. {
  17241. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  17242. {
  17243. if (genericArg->IsConstExprValue())
  17244. {
  17245. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  17246. while (genericConstValueArgs.size() < genericArgs.size())
  17247. genericConstValueArgs.push_back(BfIRValue());
  17248. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  17249. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  17250. }
  17251. else
  17252. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  17253. }
  17254. methodName += "<";
  17255. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  17256. {
  17257. if (i > 0)
  17258. methodName += ", ";
  17259. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  17260. methodName += TypeToString(type);
  17261. }
  17262. methodName += ">";
  17263. }
  17264. if ((methodName.empty()) && (methodDeclaration != NULL))
  17265. {
  17266. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  17267. {
  17268. methodName += "operator";
  17269. if (operatorDecl->mIsConvOperator)
  17270. {
  17271. methodName += " ";
  17272. methodName += TypeToString(methodInstance->mReturnType);
  17273. }
  17274. else if (operatorDecl->mOpTypeToken != NULL)
  17275. methodName += operatorDecl->mOpTypeToken->ToString();
  17276. }
  17277. }
  17278. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  17279. methodName += "$CHK";
  17280. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  17281. methodName += "$UCHK";
  17282. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  17283. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  17284. // defLine + 1, diFuncType, false, true,
  17285. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  17286. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  17287. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  17288. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  17289. defLine + 1, diFuncType, false, true,
  17290. llvm::dwarf::DW_VIRTUALITY_none,
  17291. 0,
  17292. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  17293. }
  17294. else
  17295. {
  17296. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  17297. }
  17298. }
  17299. //////////////////////////////////////////////////////////////////////////
  17300. // Head and Init get rolled into Entry afterwards.
  17301. methodState.mIRFunction = methodInstance->mIRFunction;
  17302. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  17303. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  17304. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  17305. methodState.mCurScope->mDIScope = diFunction;
  17306. auto llvmEntryBlock = methodState.mIREntryBlock;
  17307. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  17308. if (methodDef->mName == "__MALFORMED")
  17309. {
  17310. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  17311. mBfIRBuilder->SetInsertPoint(newBlock);
  17312. }
  17313. if (methodDef->mBody != NULL)
  17314. {
  17315. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17316. }
  17317. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  17318. {
  17319. // We want to be able to step into delegate invokes -- we actually step over them
  17320. if (methodDef->mName != "Invoke")
  17321. {
  17322. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  17323. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  17324. }
  17325. }
  17326. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  17327. mBfIRBuilder->ClearDebugLocation();
  17328. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  17329. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  17330. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  17331. {
  17332. int localIdx = 0;
  17333. int argIdx = 0;
  17334. Array<BfIRValue> splatAddrValues;
  17335. for ( ; argIdx < irParamCount; localIdx++)
  17336. {
  17337. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  17338. if ((isThis) && (thisType->IsValuelessType()))
  17339. isThis = false;
  17340. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() == argIdx))
  17341. {
  17342. argIdx++;
  17343. if (argIdx == irParamCount)
  17344. break;
  17345. }
  17346. BfLocalVariable* paramVar = NULL;
  17347. while (true)
  17348. {
  17349. BF_ASSERT(localIdx < methodState.mLocals.size());
  17350. paramVar = methodState.mLocals[localIdx];
  17351. if ((paramVar->mCompositeCount == -1) &&
  17352. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  17353. break;
  17354. localIdx++;
  17355. }
  17356. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  17357. {
  17358. paramVar->mIsReadOnly = true;
  17359. }
  17360. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) ||
  17361. ((!mIsComptimeModule) && (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter)));
  17362. if (paramVar->mResolvedType->IsMethodRef())
  17363. wantsAddr = false;
  17364. // if ((methodDef->mHasAppend) && (argIdx == 1))
  17365. // {
  17366. // BF_ASSERT(paramVar->mName == "appendIdx");
  17367. // wantsAddr = true;
  17368. // }
  17369. if (paramVar->mIsSplat)
  17370. {
  17371. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  17372. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  17373. BfTypeUtils::SplatIterate([&](BfType* checkType)
  17374. {
  17375. BfIRType splatIRType;
  17376. if (checkType->IsComposite())
  17377. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  17378. else
  17379. splatIRType = mBfIRBuilder->MapType(checkType);
  17380. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  17381. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  17382. if (!paramVar->mAddr)
  17383. paramVar->mAddr = allocaInst;
  17384. if (WantsLifetimes())
  17385. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  17386. splatAddrValues.push_back(allocaInst);
  17387. }, paramVar->mResolvedType);
  17388. mBfIRBuilder->SetInsertPoint(prevInsert);
  17389. }
  17390. else if (isThis)
  17391. {
  17392. if (wantsAddr)
  17393. {
  17394. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  17395. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  17396. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  17397. if (paramVar->mIsSplat)
  17398. {
  17399. //
  17400. }
  17401. else
  17402. {
  17403. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  17404. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  17405. wantPtr = true;
  17406. if (wantPtr)
  17407. {
  17408. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  17409. }
  17410. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  17411. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  17412. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  17413. paramVar->mAddr = allocaInst;
  17414. if (WantsLifetimes())
  17415. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  17416. }
  17417. mBfIRBuilder->SetInsertPoint(prevInsert);
  17418. }
  17419. }
  17420. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  17421. {
  17422. // Address doesn't change so we don't have to alloca it
  17423. BfIRType allocType;
  17424. int alignSize = mSystem->mPtrSize;
  17425. if (paramVar->mResolvedType->IsRef())
  17426. {
  17427. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  17428. }
  17429. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  17430. {
  17431. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  17432. alignSize = paramVar->mResolvedType->mAlign;
  17433. }
  17434. else
  17435. {
  17436. paramVar->mHasLocalStructBacking = true;
  17437. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  17438. if (typeInst != NULL)
  17439. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  17440. else
  17441. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  17442. }
  17443. if (wantsAddr)
  17444. {
  17445. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  17446. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  17447. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  17448. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  17449. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  17450. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  17451. paramVar->mAddr = allocaInst;
  17452. mBfIRBuilder->SetInsertPoint(prevInsert);
  17453. if (WantsLifetimes())
  17454. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  17455. }
  17456. }
  17457. else if (wantsAddr)
  17458. {
  17459. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  17460. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  17461. paramVar->mAddr = allocaInst;
  17462. }
  17463. if (paramVar->mIsSplat)
  17464. {
  17465. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17466. }
  17467. else if (paramVar->mIsLowered)
  17468. {
  17469. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17470. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17471. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  17472. argIdx++;
  17473. if (loweredTypeCode2 != BfTypeCode_None)
  17474. argIdx++;
  17475. }
  17476. else
  17477. {
  17478. argIdx++;
  17479. }
  17480. }
  17481. if (methodDef->mBody != NULL)
  17482. UpdateSrcPos(methodDef->mBody);
  17483. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17484. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  17485. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17486. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  17487. localIdx = 0;
  17488. argIdx = 0;
  17489. int splatAddrIdx = 0;
  17490. while (localIdx < (int)methodState.mLocals.size())
  17491. {
  17492. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  17493. argIdx++;
  17494. int curLocalIdx = localIdx++;
  17495. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  17496. if (!paramVar->IsParam())
  17497. continue;
  17498. if (paramVar->mCompositeCount != -1)
  17499. continue;
  17500. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  17501. if ((isThis) && (thisType->IsValuelessType()))
  17502. isThis = false;
  17503. if (paramVar->mValue.IsArg())
  17504. BF_ASSERT(paramVar->mValue.mId == argIdx);
  17505. BfIRMDNode diVariable;
  17506. if (wantsDIData)
  17507. {
  17508. String paramName = paramVar->mName;
  17509. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  17510. if (isThis)
  17511. {
  17512. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  17513. paramName = "__closure";
  17514. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  17515. {
  17516. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  17517. bool wantRef = paramVar->mResolvedType->IsComposite();
  17518. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  17519. wantRef = true;
  17520. if (wantRef)
  17521. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  17522. }
  17523. else if (!paramVar->mResolvedType->IsValueType())
  17524. {
  17525. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  17526. }
  17527. }
  17528. else
  17529. {
  17530. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  17531. {
  17532. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  17533. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  17534. diType = mBfIRBuilder->DbgCreateConstType(diType);
  17535. }
  17536. }
  17537. if (!paramVar->mIsSplat)
  17538. {
  17539. if (paramVar->mResolvedType->IsValuelessType())
  17540. {
  17541. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  17542. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  17543. }
  17544. else if (paramVar->mIsImplicitParam)
  17545. {
  17546. // Annotate this specially?
  17547. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  17548. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  17549. }
  17550. else
  17551. {
  17552. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  17553. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  17554. }
  17555. paramVar->mDbgVarInst = diVariable;
  17556. }
  17557. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  17558. {
  17559. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  17560. // {
  17561. // // Only add this placeholder if we don't have any values
  17562. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  17563. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  17564. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  17565. // }
  17566. }
  17567. }
  17568. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  17569. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  17570. {
  17571. // Write our argument value into the .addr
  17572. mBfIRBuilder->ClearDebugLocation();
  17573. if (paramVar->mIsSplat)
  17574. {
  17575. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  17576. //
  17577. }
  17578. else
  17579. {
  17580. bool handled = false;
  17581. if (paramVar->mIsLowered)
  17582. {
  17583. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17584. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17585. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  17586. {
  17587. // We have a lowered type coming in, so we have to cast the .addr before storing
  17588. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  17589. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  17590. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, primPtrType);
  17591. mBfIRBuilder->CreateStore(paramVar->mValue, primPtrVal);
  17592. if (loweredTypeCode2 != BfTypeCode_None)
  17593. {
  17594. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  17595. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  17596. BfIRValue primPtrVal2;
  17597. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  17598. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  17599. else
  17600. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  17601. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  17602. }
  17603. // We don't want to allow directly using value
  17604. paramVar->mValue = BfIRValue();
  17605. handled = true;
  17606. }
  17607. else
  17608. {
  17609. BF_ASSERT("Expected lowered");
  17610. }
  17611. }
  17612. if (!handled)
  17613. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  17614. }
  17615. }
  17616. if (methodDef->mBody != NULL)
  17617. UpdateSrcPos(methodDef->mBody);
  17618. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  17619. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  17620. else if (methodDeclaration == NULL)
  17621. UseDefaultSrcPos();
  17622. // Write our argument value into the .addr
  17623. if (paramVar->mIsSplat)
  17624. {
  17625. int splatComponentIdx = 0;
  17626. auto curArgIdx = argIdx;
  17627. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  17628. {
  17629. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  17630. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  17631. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  17632. mBfIRBuilder->ClearDebugLocation(storeInst);
  17633. if (wantsDIData)
  17634. {
  17635. BfIRMDNode diType;
  17636. if (checkType->IsComposite())
  17637. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  17638. else
  17639. diType = mBfIRBuilder->DbgGetType(checkType);
  17640. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  17641. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  17642. if (wantsDIVariables)
  17643. {
  17644. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  17645. }
  17646. }
  17647. curArgIdx++;
  17648. splatComponentIdx++;
  17649. };
  17650. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  17651. {
  17652. if (checkType->IsStruct())
  17653. {
  17654. auto checkTypeInstance = checkType->ToTypeInstance();
  17655. if (checkTypeInstance->mBaseType != NULL)
  17656. {
  17657. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  17658. }
  17659. if (checkTypeInstance->mIsUnion)
  17660. {
  17661. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  17662. if (!unionInnerType->IsValuelessType())
  17663. {
  17664. _FinishSplatsIterate(unionInnerType, name + "$u");
  17665. }
  17666. if (checkTypeInstance->IsEnum())
  17667. {
  17668. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  17669. _FinishSplatsIterate(dscrType, name + "$d");
  17670. }
  17671. }
  17672. else
  17673. {
  17674. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  17675. {
  17676. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  17677. auto fieldDef = fieldInstance->GetFieldDef();
  17678. if (fieldInstance->mDataIdx >= 0)
  17679. {
  17680. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  17681. }
  17682. }
  17683. }
  17684. }
  17685. else if (checkType->IsMethodRef())
  17686. {
  17687. auto methodRefType = (BfMethodRefType*)checkType;
  17688. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  17689. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  17690. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  17691. // {
  17692. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  17693. // if (!paramType->IsValuelessType())
  17694. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  17695. // }
  17696. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  17697. {
  17698. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  17699. String paramName = methodInstance->GetParamName(paramIdx);
  17700. if (paramName == "this")
  17701. paramName = "__this";
  17702. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  17703. {
  17704. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  17705. }
  17706. else
  17707. {
  17708. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  17709. }
  17710. }
  17711. }
  17712. else if (!checkType->IsValuelessType())
  17713. {
  17714. _FinishSplats(checkType, name);
  17715. }
  17716. };
  17717. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  17718. if (!paramVar->mConstValue)
  17719. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  17720. }
  17721. BfIRValue declareCall;
  17722. if (diVariable)
  17723. {
  17724. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  17725. {
  17726. if (!paramVar->mAddr)
  17727. {
  17728. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  17729. {
  17730. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  17731. {
  17732. // We don't need to set the location for this
  17733. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  17734. }
  17735. }
  17736. else
  17737. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  17738. }
  17739. else
  17740. {
  17741. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  17742. }
  17743. }
  17744. }
  17745. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  17746. {
  17747. // We don't allow actually assignment to "this", so we just do a single load
  17748. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  17749. // we need to store it in the stack frame for debugging purposes
  17750. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  17751. mBfIRBuilder->ClearDebugLocation(loadedThis);
  17752. paramVar->mValue = loadedThis;
  17753. }
  17754. if ((wantsDIData) && (declareCall))
  17755. mBfIRBuilder->UpdateDebugLocation(declareCall);
  17756. if (paramVar->mIsSplat)
  17757. {
  17758. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17759. }
  17760. else if (paramVar->mIsLowered)
  17761. {
  17762. argIdx++;
  17763. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17764. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17765. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  17766. if (loweredTypeCode2 != BfTypeCode_None)
  17767. argIdx++;
  17768. }
  17769. else if (!paramVar->mResolvedType->IsValuelessType())
  17770. {
  17771. argIdx++;
  17772. }
  17773. }
  17774. if (wantsDIData)
  17775. {
  17776. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  17777. }
  17778. }
  17779. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  17780. {
  17781. auto paramVar = mCurMethodState->mLocals[varIdx];
  17782. // 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
  17783. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  17784. // if (paramVar->mIsSplat)
  17785. // {
  17786. // if (wantsDIVariables)
  17787. // {
  17788. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  17789. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  17790. // }
  17791. // }
  17792. if (paramVar->mResolvedType->IsValuelessType())
  17793. {
  17794. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  17795. {
  17796. // Only add this placeholder if we don't have any values
  17797. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  17798. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  17799. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  17800. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  17801. }
  17802. }
  17803. }
  17804. if (IsTargetingBeefBackend())
  17805. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  17806. if (methodState.mClosureState != NULL)
  17807. {
  17808. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  17809. {
  17810. BfLocalVariable* localVar = new BfLocalVariable();
  17811. *localVar = constLocal;
  17812. AddLocalVariableDef(localVar, true);
  17813. }
  17814. }
  17815. bool wantsRemoveBody = false;
  17816. bool skipBody = false;
  17817. bool skipUpdateSrcPos = false;
  17818. bool skipEndChecks = false;
  17819. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  17820. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17821. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  17822. hasExternSpecifier = true;
  17823. // Allocate, clear, set classVData
  17824. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  17825. {
  17826. CreateStaticCtor();
  17827. }
  17828. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  17829. {
  17830. skipBody = true;
  17831. skipEndChecks = true;
  17832. if (HasExecutedOutput())
  17833. {
  17834. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  17835. mBfIRBuilder->ClearDebugLocation();
  17836. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  17837. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  17838. PopulateType(innerType, BfPopulateType_DataAndMethods);
  17839. mBfIRBuilder->PopulateType(mCurTypeInstance);
  17840. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  17841. if (methodInstance->mIsForeignMethodDef)
  17842. {
  17843. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  17844. }
  17845. BfTypeVector methodGenericArguments;
  17846. if (methodInstance->mMethodInfoEx != NULL)
  17847. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  17848. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  17849. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  17850. {
  17851. if (!methodInstance->mReturnType->IsValuelessType())
  17852. {
  17853. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  17854. CreateReturn(retVal);
  17855. }
  17856. else
  17857. mBfIRBuilder->CreateRetVoid();
  17858. }
  17859. else
  17860. {
  17861. auto innerMethodDef = innerMethodInstance.mMethodInstance->mMethodDef;
  17862. BF_ASSERT(innerMethodDef == methodDef);
  17863. SizedArray<BfIRValue, 8> innerParams;
  17864. BfExprEvaluator exprEvaluator(this);
  17865. if (!innerType->IsValuelessType())
  17866. {
  17867. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  17868. BfTypedValue innerVal(thisValue, innerType, true);
  17869. if (boxedType->IsBoxedStructPtr())
  17870. {
  17871. innerVal = LoadValue(innerVal);
  17872. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  17873. }
  17874. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  17875. }
  17876. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  17877. {
  17878. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  17879. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  17880. exprEvaluator.PushArg(localVal, innerParams);
  17881. }
  17882. if (!innerMethodInstance.mFunc)
  17883. {
  17884. BF_ASSERT(innerType->IsUnspecializedType());
  17885. }
  17886. else if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  17887. {
  17888. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  17889. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  17890. exprEvaluator.mReceivingValue = &returnType;
  17891. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  17892. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  17893. mBfIRBuilder->CreateRetVoid();
  17894. }
  17895. else
  17896. {
  17897. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  17898. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  17899. if (mCurMethodInstance->mReturnType->IsValueType())
  17900. retVal = LoadValue(retVal);
  17901. CreateReturn(retVal.mValue);
  17902. }
  17903. }
  17904. }
  17905. mCurMethodState->SetHadReturn(true);
  17906. mCurMethodState->mLeftBlockUncond = true;
  17907. }
  17908. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  17909. {
  17910. SetIllegalSrcPos();
  17911. mBfIRBuilder->ClearDebugLocation();
  17912. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  17913. auto thisVal = GetThis();
  17914. int prevSize = 0;
  17915. if (mContext->mBfObjectType != NULL)
  17916. {
  17917. prevSize = mContext->mBfObjectType->mInstSize;
  17918. PopulateType(mContext->mBfObjectType);
  17919. // If we have object extensions, clear out starting at the extension
  17920. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  17921. {
  17922. if (fieldInstance.GetFieldDef()->mDeclaringType->IsExtension())
  17923. {
  17924. prevSize = fieldInstance.mDataOffset;
  17925. break;
  17926. }
  17927. }
  17928. }
  17929. int curSize = mCurTypeInstance->mInstSize;
  17930. if (curSize > prevSize)
  17931. {
  17932. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  17933. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  17934. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  17935. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  17936. }
  17937. skipUpdateSrcPos = true;
  17938. }
  17939. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  17940. {
  17941. EmitCtorBody(skipBody);
  17942. }
  17943. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  17944. {
  17945. EmitDtorBody();
  17946. skipBody = true;
  17947. }
  17948. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  17949. {
  17950. EmitIteratorBlock(skipBody);
  17951. }
  17952. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  17953. {
  17954. // We need to be able to mark deleted objects
  17955. mCurMethodState->mIgnoreObjectAccessCheck = true;
  17956. }
  17957. auto customAttributes = methodInstance->GetCustomAttributes();
  17958. if (customAttributes != NULL)
  17959. {
  17960. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  17961. mCurMethodState->mIgnoreObjectAccessCheck = true;
  17962. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  17963. mCurMethodState->mDisableChecks = true;
  17964. }
  17965. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  17966. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  17967. {
  17968. // We chain even non-default ctors to the default ctors
  17969. auto defaultCtor = methodInstance;
  17970. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  17971. CallChainedMethods(defaultCtor, false);
  17972. }
  17973. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  17974. if (!mCompiler->mHasRequiredTypes)
  17975. {
  17976. // Skip processing to avoid errors
  17977. }
  17978. else if (methodDef->mBody == NULL)
  17979. {
  17980. if (methodDeclaration != NULL)
  17981. {
  17982. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  17983. {
  17984. if (operatorDeclaration->mIsConvOperator)
  17985. wantsRemoveBody = true;
  17986. }
  17987. }
  17988. bool isDllImport = false;
  17989. if ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic))
  17990. {
  17991. if (importStrNum != -1)
  17992. {
  17993. if (importKind == BfImportKind_Import_Static)
  17994. {
  17995. if (!mImportFileNames.Contains(importStrNum))
  17996. {
  17997. mImportFileNames.Add(importStrNum);
  17998. }
  17999. }
  18000. }
  18001. }
  18002. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  18003. {
  18004. CreateDllImportMethod();
  18005. }
  18006. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  18007. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  18008. {
  18009. if (mCurTypeInstance->mTypeDef->mIsFunction)
  18010. {
  18011. // Emit nothing
  18012. }
  18013. else
  18014. {
  18015. CreateDelegateInvokeMethod();
  18016. mCurMethodState->SetHadReturn(true);
  18017. mCurMethodState->mLeftBlockUncond = true;
  18018. }
  18019. }
  18020. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  18021. {
  18022. if (mCurTypeInstance->IsObject())
  18023. {
  18024. CreateDynamicCastMethod();
  18025. }
  18026. else
  18027. {
  18028. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  18029. mCurMethodState->mHadReturn = true;
  18030. }
  18031. }
  18032. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  18033. {
  18034. BfIRValue ret;
  18035. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  18036. {
  18037. // This can happen if we provide an invalid name
  18038. AssertErrorState();
  18039. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  18040. }
  18041. else
  18042. {
  18043. // Unfortunate DebugLoc shenanigans-
  18044. // 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,
  18045. // so we only set the loc on the CreateRet which gets inlined out
  18046. mBfIRBuilder->SaveDebugLocation();
  18047. mBfIRBuilder->ClearDebugLocation();
  18048. BfIRValue fromBool;
  18049. if (!mCurTypeInstance->IsTypedPrimitive())
  18050. {
  18051. fromBool = GetDefaultValue(methodInstance->mReturnType);
  18052. }
  18053. else
  18054. {
  18055. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  18056. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  18057. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  18058. }
  18059. mBfIRBuilder->RestoreDebugLocation();
  18060. ret = mBfIRBuilder->CreateRet(fromBool);
  18061. //ExtendLocalLifetimes(0);
  18062. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18063. }
  18064. mCurMethodState->SetHadReturn(true);
  18065. mCurMethodState->mLeftBlockUncond = true;
  18066. }
  18067. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  18068. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  18069. {
  18070. BfIRValue ret;
  18071. // Unfortunate DebugLoc shenanigans-
  18072. // 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,
  18073. // so we only set the loc on the CreateRet which gets inlined out
  18074. mBfIRBuilder->SaveDebugLocation();
  18075. mBfIRBuilder->ClearDebugLocation();
  18076. BfIRValue fromBool;
  18077. mBfIRBuilder->RestoreDebugLocation();
  18078. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  18079. //ExtendLocalLifetimes(0);
  18080. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18081. mCurMethodState->SetHadReturn(true);
  18082. mCurMethodState->mLeftBlockUncond = true;
  18083. }
  18084. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  18085. {
  18086. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  18087. if (HasExecutedOutput())
  18088. {
  18089. EmitEnumToStringBody();
  18090. }
  18091. mBfIRBuilder->CreateRetVoid();
  18092. mCurMethodState->SetHadReturn(true);
  18093. mCurMethodState->mLeftBlockUncond = true;
  18094. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18095. }
  18096. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  18097. {
  18098. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  18099. if (HasExecutedOutput())
  18100. {
  18101. EmitTupleToStringBody();
  18102. }
  18103. mBfIRBuilder->CreateRetVoid();
  18104. mCurMethodState->SetHadReturn(true);
  18105. mCurMethodState->mLeftBlockUncond = true;
  18106. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18107. }
  18108. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  18109. {
  18110. CreateValueTypeEqualsMethod(false);
  18111. skipBody = true;
  18112. skipEndChecks = true;
  18113. }
  18114. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  18115. {
  18116. CreateValueTypeEqualsMethod(true);
  18117. skipBody = true;
  18118. skipEndChecks = true;
  18119. }
  18120. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef->GetDefinition() == mCompiler->mValueTypeTypeDef))
  18121. {
  18122. CreateValueTypeEqualsMethod(false);
  18123. skipBody = true;
  18124. skipEndChecks = true;
  18125. }
  18126. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (mCurTypeInstance->IsDelegate()))
  18127. {
  18128. CreateDelegateEqualsMethod();
  18129. skipBody = true;
  18130. skipEndChecks = true;
  18131. }
  18132. else
  18133. {
  18134. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18135. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  18136. {
  18137. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  18138. Fail("Body expected", methodDef->mBody);
  18139. }
  18140. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  18141. {
  18142. if ((methodInstance->mReturnType->IsRef()) && (!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  18143. Fail("Auto-implemented ref property getters must declare 'mut'", methodInstance->mMethodDef->GetRefNode());
  18144. if (methodInstance->mReturnType->IsValuelessType())
  18145. {
  18146. mBfIRBuilder->CreateRetVoid();
  18147. }
  18148. else if (HasExecutedOutput())
  18149. {
  18150. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  18151. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  18152. BfFieldDef* fieldDef = NULL;
  18153. if (fieldInstance != NULL)
  18154. fieldDef = fieldInstance->GetFieldDef();
  18155. BfType* retType = methodInstance->mReturnType;
  18156. if (retType->IsRef())
  18157. retType = retType->GetUnderlyingType();
  18158. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  18159. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  18160. {
  18161. BfTypedValue lookupValue;
  18162. if (fieldDef->IsNonConstStatic())
  18163. lookupValue = ReferenceStaticField(fieldInstance);
  18164. else if (mCurTypeInstance->IsObject())
  18165. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  18166. else
  18167. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  18168. if (methodInstance->mReturnType->IsRef())
  18169. {
  18170. if ((!lookupValue.IsAddr()) && (!lookupValue.mType->IsValuelessType()))
  18171. lookupValue = MakeAddressable(lookupValue);
  18172. }
  18173. else
  18174. lookupValue = LoadOrAggregateValue(lookupValue);
  18175. CreateReturn(lookupValue.mValue);
  18176. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18177. }
  18178. else
  18179. {
  18180. // This can happen if we have two properties with the same name but different types
  18181. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  18182. EmitDefaultReturn();
  18183. }
  18184. }
  18185. else
  18186. {
  18187. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  18188. EmitDefaultReturn();
  18189. }
  18190. mCurMethodState->SetHadReturn(true);
  18191. }
  18192. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  18193. {
  18194. if ((!methodDef->mIsMutating) && (!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  18195. {
  18196. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  18197. }
  18198. else if (!mCompiler->IsAutocomplete())
  18199. {
  18200. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  18201. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  18202. auto fieldDef = fieldInstance->GetFieldDef();
  18203. auto& lastParam = mCurMethodState->mLocals.back();
  18204. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  18205. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  18206. {
  18207. BfIRValue lookupAddr;
  18208. if (fieldDef->IsNonConstStatic())
  18209. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  18210. else
  18211. {
  18212. auto thisValue = GetThis();
  18213. if (thisValue.IsSplat())
  18214. {
  18215. BFMODULE_FATAL(this, "Should not happen");
  18216. }
  18217. if (mCurTypeInstance->IsObject())
  18218. thisValue = LoadValue(thisValue);
  18219. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  18220. }
  18221. BfExprEvaluator exprEvaluator(this);
  18222. auto localVal = exprEvaluator.LoadLocal(lastParam);
  18223. localVal = LoadOrAggregateValue(localVal);
  18224. mBfIRBuilder->CreateStore(localVal.mValue, lookupAddr);
  18225. }
  18226. else if (!fieldInstance->mResolvedType->IsValuelessType())
  18227. {
  18228. // This can happen if we have two properties with the same name but different types
  18229. AssertErrorState();
  18230. }
  18231. }
  18232. }
  18233. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  18234. {
  18235. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  18236. {
  18237. if (HasCompiledOutput())
  18238. EmitGCMarkMembers();
  18239. }
  18240. else if (!mCurTypeInstance->IsObject())
  18241. {
  18242. }
  18243. }
  18244. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  18245. {
  18246. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  18247. {
  18248. if (HasCompiledOutput())
  18249. EmitGCFindTLSMembers();
  18250. }
  18251. }
  18252. }
  18253. }
  18254. else if (!skipBody)
  18255. {
  18256. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  18257. bool wantsRetVal = true;
  18258. if ((mIsComptimeModule) && (methodDef->mMethodType != BfMethodType_CtorCalcAppend))
  18259. wantsRetVal = false;
  18260. else if (mCurMethodInstance->mReturnType->IsVar())
  18261. wantsRetVal = false;
  18262. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  18263. {
  18264. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  18265. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  18266. {
  18267. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  18268. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  18269. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst);
  18270. mBfIRBuilder->ClearDebugLocation(storeInst);
  18271. mCurMethodState->mRetValAddr = allocaInst;
  18272. }
  18273. else if (wantsRetVal)
  18274. {
  18275. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  18276. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  18277. }
  18278. }
  18279. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  18280. {
  18281. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  18282. BfGetSymbolReferenceKind prevSymbolKind;
  18283. BfAutoComplete* prevAutoComplete;
  18284. if (mCompiler->mResolvePassData != NULL)
  18285. {
  18286. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  18287. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  18288. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  18289. }
  18290. EmitCtorCalcAppend();
  18291. if (mCompiler->mResolvePassData != NULL)
  18292. {
  18293. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  18294. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  18295. }
  18296. }
  18297. else if (!isEmptyBodied)
  18298. {
  18299. if (!mCurMethodState->mIRExitBlock)
  18300. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  18301. bool isExpressionBody = false;
  18302. if (methodDeclaration != NULL)
  18303. {
  18304. if (methodDeclaration->mFatArrowToken != NULL)
  18305. isExpressionBody = true;
  18306. }
  18307. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  18308. {
  18309. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  18310. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  18311. isExpressionBody = true;
  18312. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  18313. {
  18314. isExpressionBody = true;
  18315. }
  18316. }
  18317. else
  18318. {
  18319. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  18320. {
  18321. if (!block->mChildArr.IsEmpty())
  18322. {
  18323. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  18324. {
  18325. if (exprStmt->mTrailingSemicolon == NULL)
  18326. isExpressionBody = true;
  18327. }
  18328. }
  18329. }
  18330. else
  18331. isExpressionBody = true;
  18332. }
  18333. DoCEEmit(methodInstance);
  18334. if (methodInstance->mCeCancelled)
  18335. mIgnoreErrors = true;
  18336. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  18337. {
  18338. while (fieldDtorBody != NULL)
  18339. {
  18340. VisitEmbeddedStatement(fieldDtorBody->mBody);
  18341. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  18342. }
  18343. }
  18344. else if (!isExpressionBody)
  18345. {
  18346. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  18347. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  18348. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  18349. VisitCodeBlock(bodyBlock);
  18350. }
  18351. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  18352. {
  18353. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  18354. // {
  18355. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  18356. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  18357. // }
  18358. auto expectingType = mCurMethodInstance->mReturnType;
  18359. // What was this error for?
  18360. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  18361. // {
  18362. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  18363. // }
  18364. BfEvalExprFlags exprEvalFlags = BfEvalExprFlags_AllowRefExpr;
  18365. if (expectingType->IsVoid())
  18366. {
  18367. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  18368. bool wasReturnGenericParam = false;
  18369. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  18370. {
  18371. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  18372. }
  18373. else
  18374. {
  18375. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  18376. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  18377. wasReturnGenericParam = true;
  18378. }
  18379. // If we the void return was from a generic specialization, allow us to return a void result,
  18380. // otherwise treat expression as though it must be a statement
  18381. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  18382. if (isStatement)
  18383. expectingType = NULL;
  18384. }
  18385. UpdateSrcPos(expressionBody);
  18386. auto retVal = CreateValueFromExpression(expressionBody, expectingType, exprEvalFlags);
  18387. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  18388. {
  18389. mCurMethodState->mHadReturn = true;
  18390. retVal = LoadOrAggregateValue(retVal);
  18391. EmitReturn(retVal);
  18392. }
  18393. }
  18394. }
  18395. }
  18396. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  18397. if (skipUpdateSrcPos)
  18398. {
  18399. // Skip
  18400. }
  18401. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  18402. UpdateSrcPos(bodyBlock->mCloseBrace);
  18403. else if (methodDef->mBody != NULL)
  18404. UpdateSrcPos(methodDef->mBody);
  18405. else if (methodDeclaration != NULL)
  18406. UpdateSrcPos(methodDeclaration);
  18407. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  18408. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  18409. else
  18410. UseDefaultSrcPos();
  18411. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  18412. {
  18413. if (mCurMethodState->mRetVal)
  18414. {
  18415. mCurMethodState->SetHadReturn(true);
  18416. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  18417. mBfIRBuilder->CreateRet(retVal);
  18418. }
  18419. else
  18420. AssertErrorState();
  18421. }
  18422. if (!mCurMethodState->mHadReturn)
  18423. {
  18424. // Clear off the stackallocs that have occurred after a scopeData break
  18425. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  18426. }
  18427. if (mCurMethodState->mIRExitBlock)
  18428. {
  18429. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  18430. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  18431. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  18432. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  18433. if ((!mCurMethodState->mDIRetVal) && (wantsDIData))
  18434. CreateDIRetVal();
  18435. }
  18436. for (auto localVar : mCurMethodState->mLocals)
  18437. {
  18438. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  18439. {
  18440. //
  18441. }
  18442. else if ((skipEndChecks) || (methodDef->mBody == NULL))
  18443. break;
  18444. LocalVariableDone(localVar, true);
  18445. }
  18446. if (mCurMethodState->mIRExitBlock)
  18447. {
  18448. if ((mCurMethodState->mRetVal) &&
  18449. ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() == -1)))
  18450. {
  18451. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  18452. CreateReturn(loadedVal);
  18453. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18454. if (mCurMethodState->mDIRetVal)
  18455. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  18456. }
  18457. else
  18458. {
  18459. // Have something on the last line to step onto
  18460. if (mHasFullDebugInfo)
  18461. {
  18462. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  18463. UpdateSrcPos(bodyBlock->mCloseBrace);
  18464. EmitEnsureInstructionAt();
  18465. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  18466. {
  18467. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  18468. mBfIRBuilder->EnsureFunctionPatchable();
  18469. }
  18470. }
  18471. mBfIRBuilder->CreateRetVoid();
  18472. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18473. if (mCurMethodState->mDIRetVal)
  18474. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  18475. }
  18476. }
  18477. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  18478. {
  18479. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  18480. {
  18481. if ((!mIsComptimeModule) && (irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  18482. {
  18483. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  18484. mBfIRBuilder->EnsureFunctionPatchable();
  18485. }
  18486. mBfIRBuilder->CreateRetVoid();
  18487. }
  18488. }
  18489. else
  18490. {
  18491. if (!mCurMethodState->mHadReturn)
  18492. {
  18493. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  18494. if (bodyBlock != NULL)
  18495. {
  18496. if (bodyBlock->mCloseBrace != NULL)
  18497. {
  18498. BfAstNode* target = bodyBlock->mCloseBrace;
  18499. if (!mCompiler->mHasRequiredTypes)
  18500. {
  18501. AddFailType(mCurTypeInstance);
  18502. mHadBuildError = true;
  18503. }
  18504. else
  18505. Fail("Method must return value", target);
  18506. }
  18507. else
  18508. {
  18509. // It's possible to not have a closing brace if the method ends in an EOF
  18510. AssertErrorState();
  18511. }
  18512. }
  18513. }
  18514. }
  18515. // Move 'init' into 'entry'
  18516. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  18517. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  18518. if (((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType())) &&
  18519. (!mIsComptimeModule))
  18520. {
  18521. // Don't keep instructions for unspecialized types
  18522. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  18523. }
  18524. // Avoid linking any internal funcs that were just supposed to be comptime-accessible
  18525. /*if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  18526. wantsRemoveBody = true;*/
  18527. if ((hasExternSpecifier) && (!skipBody))
  18528. {
  18529. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  18530. // incase it gets called later by some hot-loaded coded
  18531. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()) && (mCurTypeInstance != mContext->mBfObjectType))
  18532. {
  18533. if (!mCurMethodInstance->mMethodDef->mName.StartsWith("Comptime_"))
  18534. CreateFakeCallerMethod(mangledName);
  18535. }
  18536. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  18537. }
  18538. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  18539. {
  18540. // We only need the DLL stub when we may be hot swapping
  18541. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  18542. }
  18543. else if (wantsRemoveBody)
  18544. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  18545. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  18546. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  18547. // unspecialized types
  18548. if (((mCurTypeInstance->IsUnspecializedType()) && (!mIsComptimeModule)) ||
  18549. (mCurTypeInstance->IsInterface()))
  18550. {
  18551. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  18552. methodInstance->mIRFunction = BfIRFunction();
  18553. }
  18554. CheckAddFailType();
  18555. if (mHadBuildError)
  18556. prevHadBuildError.CancelRestore();
  18557. if (mHadBuildWarning)
  18558. prevHadWarning.CancelRestore();
  18559. if (!methodDef->mIsLocalMethod)
  18560. ProcessMethod_ProcessDeferredLocals();
  18561. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  18562. if (methodState.mHotDataReferenceBuilder != NULL)
  18563. {
  18564. AddHotDataReferences(&hotDataReferenceBuilder);
  18565. }
  18566. else
  18567. {
  18568. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  18569. {
  18570. // Remove the hot method data
  18571. auto hotMethod = methodInstance->mHotMethod;
  18572. auto prevMethod = hotMethod->mPrevVersion;
  18573. if (prevMethod != NULL)
  18574. {
  18575. // If there's a prev method then pull its data into the main HotMethod.
  18576. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  18577. // over to the main HotMethod definition to keep the HotMethod address
  18578. // invariant
  18579. for (auto ref : hotMethod->mReferences)
  18580. ref->Deref();
  18581. hotMethod->mReferences.Clear();
  18582. BF_ASSERT(prevMethod->mRefCount == 1);
  18583. hotMethod->mReferences = prevMethod->mReferences;
  18584. if (hotMethod->mSrcTypeVersion != NULL)
  18585. hotMethod->mSrcTypeVersion->Deref();
  18586. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  18587. prevMethod->mSrcTypeVersion = NULL;
  18588. prevMethod->mReferences.Clear();
  18589. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  18590. prevMethod->mPrevVersion = NULL;
  18591. prevMethod->Deref();
  18592. }
  18593. hotMethod->Deref();
  18594. methodInstance->mHotMethod = NULL;
  18595. }
  18596. }
  18597. }
  18598. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  18599. {
  18600. String name;
  18601. bool found = false;
  18602. auto checkMethodState = mCurMethodState;
  18603. while (checkMethodState != NULL)
  18604. {
  18605. if (checkMethodState->mClosureState == NULL)
  18606. break;
  18607. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  18608. {
  18609. found = true;
  18610. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  18611. break;
  18612. }
  18613. checkMethodState = checkMethodState->mPrevMethodState;
  18614. }
  18615. if (!found)
  18616. name += mCurMethodInstance->mMethodDef->mName;
  18617. int prevSepPos = (int)name.LastIndexOf('$');
  18618. if (prevSepPos != -1)
  18619. {
  18620. name.RemoveToEnd(prevSepPos);
  18621. }
  18622. name += "@";
  18623. name += baseName;
  18624. HashContext hashCtx;
  18625. if (anchorNode != NULL)
  18626. {
  18627. hashCtx.Mixin(anchorNode->GetStartCharId());
  18628. }
  18629. //
  18630. {
  18631. auto checkMethodState = declMethodState;
  18632. auto checkMixinState = declMixinState;
  18633. while (checkMethodState != NULL)
  18634. {
  18635. if (checkMixinState != NULL)
  18636. {
  18637. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  18638. }
  18639. checkMethodState = checkMethodState->mPrevMethodState;
  18640. if (checkMethodState != NULL)
  18641. checkMixinState = checkMethodState->mMixinState;
  18642. }
  18643. }
  18644. auto rootMethodState = mCurMethodState->GetRootMethodState();
  18645. if ((rootMethodState != NULL) && (rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  18646. {
  18647. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  18648. {
  18649. StringT<128> genericTypeName;
  18650. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  18651. hashCtx.MixinStr(genericTypeName);
  18652. }
  18653. }
  18654. uint64 hashVal = hashCtx.Finish64();
  18655. name += "$";
  18656. name += BfTypeUtils::HashEncode64(hashVal);
  18657. return name;
  18658. }
  18659. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  18660. {
  18661. if (localMethod->mMethodDef != NULL)
  18662. return localMethod->mMethodDef;
  18663. auto rootMethodState = mCurMethodState->GetRootMethodState();
  18664. auto declMethodState = localMethod->mDeclMethodState;
  18665. auto declMixinState = localMethod->mDeclMixinState;
  18666. auto typeInst = mCurTypeInstance;
  18667. BfAstNode* body = NULL;
  18668. BfAstNode* anchorNode = NULL;
  18669. auto _AllocDirectTypeRef = [&](BfType* type)
  18670. {
  18671. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  18672. directTypeRef->Init(type);
  18673. return directTypeRef;
  18674. };
  18675. auto methodDeclaration = localMethod->mMethodDeclaration;
  18676. if (methodDeclaration != NULL)
  18677. {
  18678. body = methodDeclaration->mBody;
  18679. anchorNode = methodDeclaration->mOpenParen;
  18680. }
  18681. else
  18682. {
  18683. body = localMethod->mLambdaBindExpr->mBody;
  18684. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  18685. }
  18686. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  18687. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  18688. BfMethodDef* methodDef;
  18689. BfMethodDef* outerMethodDef = NULL;
  18690. if (localMethod->mOuterLocalMethod != NULL)
  18691. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  18692. else if (rootMethodState->mMethodInstance != NULL)
  18693. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  18694. if (methodDeclaration != NULL)
  18695. {
  18696. BfDefBuilder defBuilder(mCompiler->mSystem);
  18697. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  18698. defBuilder.mPassInstance = mCompiler->mPassInstance;
  18699. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  18700. defBuilder.mCurDeclaringTypeDef = defBuilder.mCurTypeDef;
  18701. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  18702. }
  18703. else
  18704. {
  18705. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  18706. methodDef = new BfMethodDef();
  18707. methodDef->mName = localMethod->mMethodName;
  18708. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  18709. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  18710. methodDef->mBody = body;
  18711. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  18712. {
  18713. auto paramType = invokeMethod->GetParamType(paramIdx);
  18714. String paramName;
  18715. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  18716. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  18717. else
  18718. paramName = invokeMethod->GetParamName(paramIdx);
  18719. auto paramDef = new BfParameterDef();
  18720. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  18721. paramDef->mName = paramName;
  18722. methodDef->mParams.Add(paramDef);
  18723. }
  18724. if (outerMethodDef != NULL)
  18725. {
  18726. for (auto genericParam : outerMethodDef->mGenericParams)
  18727. {
  18728. auto* copiedGenericParamDef = new BfGenericParamDef();
  18729. *copiedGenericParamDef = *genericParam;
  18730. methodDef->mGenericParams.Add(copiedGenericParamDef);
  18731. }
  18732. }
  18733. }
  18734. methodDef->mIdx = ~methodLocalIdx;
  18735. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  18736. methodDef->mName = localMethod->mExpectedFullName;
  18737. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  18738. //
  18739. // if (!localMethod->mExpectedFullName.IsEmpty())
  18740. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  18741. methodDef->mIsStatic = true;
  18742. methodDef->mIsLocalMethod = true;
  18743. methodDef->mIsVirtual = false;
  18744. localMethod->mMethodDef = methodDef;
  18745. auto methodInstanceGroup = new BfMethodInstanceGroup();
  18746. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  18747. methodInstanceGroup->mMethodIdx = -1;
  18748. methodInstanceGroup->mOwner = mCurTypeInstance;
  18749. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  18750. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  18751. {
  18752. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  18753. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  18754. }
  18755. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  18756. {
  18757. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  18758. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  18759. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  18760. {
  18761. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  18762. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  18763. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  18764. autoComplete->mDefType = typeInst->mTypeDef;
  18765. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  18766. autoComplete->mReplaceLocalId = methodLocalIdx;
  18767. }
  18768. }
  18769. return localMethod->mMethodDef;
  18770. }
  18771. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  18772. {
  18773. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  18774. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  18775. auto rootMethodState = mCurMethodState->GetRootMethodState();
  18776. auto declMethodState = localMethod->mDeclMethodState;
  18777. auto declMixinState = localMethod->mDeclMixinState;
  18778. auto callerMethodState = mCurMethodState;
  18779. auto typeInst = mCurTypeInstance;
  18780. if (mCurMethodState->mMixinState != NULL)
  18781. {
  18782. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  18783. }
  18784. auto methodDef = GetLocalMethodDef(localMethod);
  18785. BfAstNode* body = NULL;
  18786. auto methodDeclaration = localMethod->mMethodDeclaration;
  18787. if (methodDeclaration != NULL)
  18788. {
  18789. body = methodDeclaration->mBody;
  18790. }
  18791. else
  18792. {
  18793. body = localMethod->mLambdaBindExpr->mBody;
  18794. }
  18795. bool hadConcreteInterfaceGenericArgument = false;
  18796. BfTypeVector sanitizedMethodGenericArguments;
  18797. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  18798. // version of this method for this pass through the outermost method
  18799. int dependentGenericStartIdx = 0;
  18800. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  18801. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  18802. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  18803. if (methodGenericArguments.size() == 0)
  18804. {
  18805. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  18806. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  18807. }
  18808. else
  18809. {
  18810. int genericArgIdx = 0;
  18811. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  18812. // {
  18813. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  18814. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  18815. // }
  18816. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  18817. {
  18818. auto genericArgType = methodGenericArguments[genericArgIdx];
  18819. BF_ASSERT(!genericArgType->IsRef());
  18820. if (genericArgType->IsConcreteInterfaceType())
  18821. {
  18822. hadConcreteInterfaceGenericArgument = true;
  18823. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  18824. genericArgType = concreteInterfaceType->mInterface;
  18825. }
  18826. sanitizedMethodGenericArguments.push_back(genericArgType);
  18827. }
  18828. }
  18829. bool wantPrematureMethodInstance = false;
  18830. if (!force)
  18831. {
  18832. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  18833. }
  18834. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  18835. bool isDefaultPass = true;
  18836. BfTypeVector lookupMethodGenericArguments;
  18837. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  18838. {
  18839. auto genericArgType = methodGenericArguments[genericArgIdx];
  18840. BF_ASSERT(!genericArgType->IsRef());
  18841. lookupMethodGenericArguments.Add(genericArgType);
  18842. if (genericArgType->IsGenericParam())
  18843. {
  18844. auto genericParam = (BfGenericParamType*)genericArgType;
  18845. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  18846. isDefaultPass = false;
  18847. }
  18848. else
  18849. {
  18850. isDefaultPass = false;
  18851. }
  18852. }
  18853. bool hadExistingMethodInstance = false;
  18854. if (methodInstance != NULL)
  18855. {
  18856. hadExistingMethodInstance = true;
  18857. }
  18858. else
  18859. {
  18860. if (isDefaultPass)
  18861. {
  18862. methodInstance = methodInstGroup->mDefault;
  18863. if (methodInstance != NULL)
  18864. {
  18865. hadExistingMethodInstance = true;
  18866. }
  18867. else
  18868. {
  18869. methodInstance = new BfMethodInstance();
  18870. methodInstGroup->mDefault = methodInstance;
  18871. }
  18872. }
  18873. else
  18874. {
  18875. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  18876. if (methodInstGroup->mMethodSpecializationMap == NULL)
  18877. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  18878. BfMethodInstance** methodInstancePtr = NULL;
  18879. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  18880. {
  18881. methodInstance = *methodInstancePtr;
  18882. hadExistingMethodInstance = true;
  18883. }
  18884. else
  18885. {
  18886. methodInstance = new BfMethodInstance();
  18887. *methodInstancePtr = methodInstance;
  18888. }
  18889. }
  18890. }
  18891. if (hadExistingMethodInstance)
  18892. {
  18893. if ((!methodInstance->mDisallowCalling) ||
  18894. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  18895. return BfModuleMethodInstance(methodInstance);
  18896. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  18897. }
  18898. else
  18899. {
  18900. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  18901. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  18902. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  18903. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  18904. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  18905. methodInstance->mMethodDef = methodDef;
  18906. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  18907. if (hadConcreteInterfaceGenericArgument)
  18908. methodInstance->mIgnoreBody = true;
  18909. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  18910. for (auto genericArg : sanitizedMethodGenericArguments)
  18911. {
  18912. if (genericArg->IsPrimitiveType())
  18913. genericArg = GetWrappedStructType(genericArg);
  18914. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  18915. }
  18916. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  18917. {
  18918. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  18919. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  18920. }
  18921. SetupMethodIdHash(methodInstance);
  18922. }
  18923. auto _SetupMethodInstance = [&]()
  18924. {
  18925. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  18926. // Generic constraints
  18927. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  18928. {
  18929. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  18930. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  18931. }
  18932. };
  18933. //////////////////////////////////////////////////////////////////////////
  18934. auto _VisitLambdaBody = [&]()
  18935. {
  18936. if (localMethod->mDeclOnly)
  18937. return;
  18938. if (mCompiler->mCanceling)
  18939. return;
  18940. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  18941. {
  18942. VisitCodeBlock(blockBody);
  18943. }
  18944. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  18945. {
  18946. BfType* expectType = NULL;
  18947. if (!methodInstance->mReturnType->IsVoid())
  18948. expectType = methodInstance->mReturnType;
  18949. CreateValueFromExpression(bodyExpr, expectType, BfEvalExprFlags_AllowRefExpr);
  18950. }
  18951. };
  18952. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  18953. {
  18954. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  18955. auto result = ResolveTypeRef(typeRef);
  18956. if (result == NULL)
  18957. result = mContext->mBfObjectType;
  18958. return result;
  18959. };
  18960. BfTypeInstance* outerClosure = NULL;
  18961. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  18962. outerClosure = declMethodState->mClosureState->mClosureType;
  18963. BfMethodState methodState;
  18964. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  18965. BfIRFunctionType funcType;
  18966. auto voidType = GetPrimitiveType(BfTypeCode_None);
  18967. SizedArray<BfIRType, 0> paramTypes;
  18968. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  18969. mBfIRBuilder->SaveDebugLocation();
  18970. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  18971. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  18972. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  18973. BfDeferredLocalAssignData deferredLocalAssignData;
  18974. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  18975. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  18976. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  18977. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  18978. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  18979. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  18980. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  18981. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  18982. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  18983. methodState.mIRFunction = declMethodState->mIRFunction;
  18984. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  18985. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  18986. {
  18987. methodState.mCurScope->mAstBlock = blockBody;
  18988. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  18989. }
  18990. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  18991. BfClosureState closureState;
  18992. if (methodDef->mMethodType == BfMethodType_Mixin)
  18993. {
  18994. if (declMethodState != NULL)
  18995. {
  18996. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  18997. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  18998. else if (declMethodState->mMethodInstance != NULL)
  18999. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  19000. }
  19001. }
  19002. if (closureState.mReturnType == NULL)
  19003. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  19004. closureState.mCapturing = true;
  19005. closureState.mLocalMethod = localMethod;
  19006. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  19007. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  19008. methodState.mClosureState = &closureState;
  19009. closureState.mClosureType = outerClosure;
  19010. int outerLocalsCount = (int)methodState.mLocals.size();
  19011. if (!hadExistingMethodInstance)
  19012. {
  19013. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  19014. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  19015. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  19016. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  19017. auto declareModule = this;
  19018. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  19019. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  19020. BF_ASSERT(declareModule != NULL);
  19021. methodInstance->mDeclModule = declareModule;
  19022. _SetupMethodInstance();
  19023. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  19024. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  19025. }
  19026. if (wantPrematureMethodInstance)
  19027. {
  19028. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  19029. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  19030. // its true method instance
  19031. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  19032. //BF_ASSERT(moduleMethodInstance);
  19033. return BfModuleMethodInstance(methodInstance);
  19034. }
  19035. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  19036. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  19037. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  19038. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  19039. closureState.mClosureMethodDef = methodDef;
  19040. bool wantsVisitBody = true;
  19041. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  19042. wantsVisitBody = false;
  19043. if (methodInstance->IsOrInUnspecializedVariation())
  19044. wantsVisitBody = false;
  19045. bool allowCapture = (methodDeclaration == NULL) || (methodDeclaration->mStaticSpecifier == NULL);
  19046. if (wantsVisitBody)
  19047. {
  19048. BP_ZONE("VisitLambdaBody");
  19049. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  19050. // this capture stage for each of those times
  19051. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  19052. /*
  19053. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  19054. // that will not occur during the actual lambda method generation, for example: returning a value
  19055. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  19056. // our AST nodes will still be visited
  19057. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  19058. */
  19059. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  19060. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  19061. mBfIRBuilder->SaveDebugLocation();
  19062. closureState.mCaptureVisitingBody = true;
  19063. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  19064. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  19065. methodState.mMethodInstance = methodInstance;
  19066. NewScopeState();
  19067. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  19068. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  19069. {
  19070. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  19071. for (auto localDef : methodState.mLocals)
  19072. {
  19073. if (localDef->mResolvedType->IsVar())
  19074. continue;
  19075. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  19076. }
  19077. }
  19078. // Keep outs for being marked as assigned
  19079. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19080. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  19081. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  19082. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  19083. if (!mIgnoreErrors)
  19084. localMethod->mDidBodyErrorPass = true;
  19085. _VisitLambdaBody();
  19086. RestoreScopeState();
  19087. closureState.mCaptureVisitingBody = false;
  19088. mBfIRBuilder->RestoreDebugLocation();
  19089. }
  19090. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  19091. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  19092. {
  19093. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  19094. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  19095. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  19096. }
  19097. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  19098. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  19099. closureState.mClosureMethodDef = NULL;
  19100. for (auto methodInstance : closureState.mLocalMethodRefs)
  19101. {
  19102. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  19103. }
  19104. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  19105. prevIgnoreWrites.Restore();
  19106. std::multiset<BfClosureCapturedEntry> capturedEntries;
  19107. //
  19108. {
  19109. auto varMethodState = declMethodState;
  19110. while (varMethodState != NULL)
  19111. {
  19112. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  19113. {
  19114. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  19115. methodDef->mIsStatic = false;
  19116. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  19117. methodDef->mIsMutating = true;
  19118. }
  19119. bool copyOuterCaptures = false;
  19120. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  19121. {
  19122. auto localVar = varMethodState->mLocals[localIdx];
  19123. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  19124. {
  19125. if (!allowCapture)
  19126. {
  19127. if ((!localVar->mIsStatic) && (!localVar->mConstValue))
  19128. continue;
  19129. }
  19130. if (localVar->mIsThis)
  19131. {
  19132. // We can only set mutating if our owning type is mutating
  19133. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  19134. {
  19135. if (typeInst->IsValueType())
  19136. {
  19137. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  19138. methodDef->mIsMutating = true;
  19139. }
  19140. }
  19141. methodDef->mIsStatic = false;
  19142. continue;
  19143. }
  19144. if ((localVar->mIsThis) && (outerClosure != NULL))
  19145. {
  19146. continue;
  19147. }
  19148. if ((localVar->mConstValue) || (localVar->mIsStatic) || (localVar->mResolvedType->IsValuelessType()))
  19149. {
  19150. closureState.mConstLocals.push_back(*localVar);
  19151. continue;
  19152. }
  19153. BfClosureCapturedEntry capturedEntry;
  19154. auto capturedType = localVar->mResolvedType;
  19155. bool captureByRef = false;
  19156. if (!capturedType->IsRef())
  19157. {
  19158. if (localVar->mIsThis)
  19159. {
  19160. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  19161. captureByRef = true;
  19162. }
  19163. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  19164. captureByRef = true;
  19165. }
  19166. else
  19167. {
  19168. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  19169. {
  19170. capturedType = ((BfRefType*)capturedType)->mElementType;
  19171. }
  19172. }
  19173. if (captureByRef)
  19174. {
  19175. //capturedEntry.mIsByReference = true;
  19176. capturedType = CreateRefType(capturedType);
  19177. }
  19178. else
  19179. {
  19180. //capturedEntry.mIsByReference = false;
  19181. }
  19182. capturedEntry.mNameNode = localVar->mNameNode;
  19183. capturedEntry.mType = capturedType;
  19184. capturedEntry.mName = localVar->mName;
  19185. //capturedEntry.mLocalVarDef = localVar;
  19186. capturedEntries.insert(capturedEntry);
  19187. }
  19188. }
  19189. varMethodState = varMethodState->mPrevMethodState;
  19190. if ((varMethodState == NULL) ||
  19191. (varMethodState->mMixinState != NULL) ||
  19192. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  19193. break;
  19194. }
  19195. }
  19196. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  19197. {
  19198. auto fieldDef = copyField->GetFieldDef();
  19199. BfClosureCapturedEntry capturedEntry;
  19200. capturedEntry.mName = copyField->GetFieldDef()->mName;
  19201. capturedEntry.mType = copyField->mResolvedType;
  19202. if (capturedEntry.mType->IsRef())
  19203. {
  19204. // Keep by ref
  19205. }
  19206. else if (!fieldDef->mIsReadOnly)
  19207. {
  19208. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  19209. }
  19210. capturedEntries.insert(capturedEntry);
  19211. }
  19212. int captureIdx = 0;
  19213. for (auto& capturedEntry : capturedEntries)
  19214. {
  19215. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  19216. }
  19217. /*if (isDefaultPass)
  19218. {
  19219. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  19220. int captureIdx = 0;
  19221. for (auto& capturedEntry : capturedEntries)
  19222. {
  19223. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  19224. BfParameterDef* paramDef = new BfParameterDef();
  19225. paramDef->mName = capturedEntry.mName;
  19226. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  19227. directTypeRef->mType = capturedEntry.mType;
  19228. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  19229. paramDef->mTypeRef = directTypeRef;
  19230. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  19231. methodDef->mParams.Insert(captureIdx, paramDef);
  19232. captureIdx++;
  19233. }
  19234. }
  19235. else
  19236. {
  19237. auto defaultMethodInstance = methodInstGroup->mDefault;
  19238. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  19239. }*/
  19240. methodState.Reset();
  19241. closureState.mCapturing = false;
  19242. //////////////////////////////////////////////////////////////////////////
  19243. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  19244. if (methodInstance->mReturnType != NULL)
  19245. {
  19246. BF_ASSERT(methodInstance->mDisallowCalling);
  19247. // We did a premature declaration (without captures)
  19248. methodInstance->UndoDeclaration();
  19249. methodInstance->mDisallowCalling = false;
  19250. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  19251. }
  19252. auto declareModule = this;
  19253. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  19254. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  19255. BF_ASSERT(declareModule != NULL);
  19256. methodInstance->mDeclModule = declareModule;
  19257. _SetupMethodInstance();
  19258. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  19259. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  19260. closureState.mReturnType = methodInstance->mReturnType;
  19261. mCompiler->mStats.mMethodsQueued++;
  19262. mCompiler->UpdateCompletion();
  19263. declareModule->mIncompleteMethodCount++;
  19264. mCompiler->mStats.mMethodsProcessed++;
  19265. if (!methodInstance->mIsReified)
  19266. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  19267. auto deferMethodState = rootMethodState;
  19268. // 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)
  19269. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  19270. (methodDef->mMethodType != BfMethodType_Mixin) &&
  19271. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)) &&
  19272. (!mCompiler->IsDataResolvePass()))
  19273. {
  19274. BP_ZONE("BfDeferredLocalMethod:create");
  19275. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  19276. deferredLocalMethod->mLocalMethod = localMethod;
  19277. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  19278. deferredLocalMethod->mMethodInstance = methodInstance;
  19279. auto checkMethodState = declMethodState;
  19280. while (checkMethodState != NULL)
  19281. {
  19282. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  19283. {
  19284. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  19285. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  19286. }
  19287. if (checkMethodState->mMixinState != NULL)
  19288. {
  19289. BfMixinRecord mixinRecord;
  19290. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  19291. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  19292. }
  19293. checkMethodState = checkMethodState->mPrevMethodState;
  19294. }
  19295. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  19296. }
  19297. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  19298. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  19299. mBfIRBuilder->RestoreDebugLocation();
  19300. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  19301. {
  19302. auto checkMethodState = mCurMethodState;
  19303. while (checkMethodState != NULL)
  19304. {
  19305. BfLocalMethod* nextLocalMethod = NULL;
  19306. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  19307. {
  19308. while (nextLocalMethod != NULL)
  19309. {
  19310. auto checkLocalMethod = nextLocalMethod;
  19311. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  19312. if (checkLocalMethod == localMethod)
  19313. continue;
  19314. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  19315. continue;
  19316. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  19317. if (checkMethodInstance == NULL)
  19318. continue; // Not generated yet
  19319. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  19320. {
  19321. String error = "Method already declared with the same parameter types";
  19322. auto bfError = Fail(error, methodInstance->mMethodDef->GetRefNode(), true);
  19323. if ((bfError != NULL) && (methodInstance->mMethodDef->GetRefNode() != checkMethodInstance->mMethodDef->GetRefNode()))
  19324. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  19325. }
  19326. }
  19327. }
  19328. checkMethodState = checkMethodState->mPrevMethodState;
  19329. }
  19330. }
  19331. return BfModuleMethodInstance(methodInstance);
  19332. }
  19333. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  19334. {
  19335. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  19336. return 0;
  19337. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19338. int rootMethodGenericParamCount = 0;
  19339. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  19340. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  19341. if (mCurMethodInstance == NULL)
  19342. return rootMethodGenericParamCount;
  19343. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  19344. return rootMethodGenericParamCount;
  19345. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  19346. if (callerLocalMethod == NULL)
  19347. return rootMethodGenericParamCount;
  19348. BfLocalMethod* calledLocalMethod = NULL;
  19349. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  19350. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  19351. {
  19352. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  19353. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  19354. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  19355. }
  19356. return rootMethodGenericParamCount;
  19357. }
  19358. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  19359. {
  19360. auto methodDef = methodInstance->mMethodDef;
  19361. auto customAttributes = methodInstance->GetCustomAttributes();
  19362. if (customAttributes != NULL)
  19363. return;
  19364. auto methodDeclaration = methodDef->GetMethodDeclaration();
  19365. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  19366. auto typeInstance = methodInstance->GetOwner();
  19367. BfTypeState typeState(typeInstance);
  19368. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  19369. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  19370. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  19371. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  19372. BfAttributeDirective* attributeDirective = NULL;
  19373. if (methodDeclaration != NULL)
  19374. attributeDirective = methodDeclaration->mAttributes;
  19375. else if (propertyMethodDeclaration != NULL)
  19376. {
  19377. attributeDirective = propertyMethodDeclaration->mAttributes;
  19378. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  19379. {
  19380. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  19381. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  19382. }
  19383. }
  19384. if (attributeDirective != NULL)
  19385. {
  19386. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  19387. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  19388. if ((methodInstance == methodInstance->mMethodInstanceGroup->mDefault) && (methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes != NULL))
  19389. {
  19390. // Take over prevoiusly-generated custom attributes
  19391. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes;
  19392. methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes = NULL;
  19393. }
  19394. else
  19395. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  19396. }
  19397. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mPropertyDeclaration->mAttributes != NULL) && ((attrTarget & BfAttributeTargets_Property) == 0))
  19398. {
  19399. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes != NULL)
  19400. {
  19401. GetCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  19402. }
  19403. else
  19404. {
  19405. methodInstance->GetMethodInfoEx()->mMethodCustomAttributes = new BfMethodCustomAttributes();
  19406. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  19407. }
  19408. }
  19409. customAttributes = methodInstance->GetCustomAttributes();
  19410. if (customAttributes == NULL)
  19411. {
  19412. auto owner = methodInstance->GetOwner();
  19413. if ((owner->IsDelegate()) || (owner->IsFunction()))
  19414. customAttributes = owner->mCustomAttributes;
  19415. }
  19416. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  19417. if (customAttributes != NULL)
  19418. {
  19419. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  19420. if (linkNameAttr != NULL)
  19421. {
  19422. if (linkNameAttr->mCtorArgs.size() == 1)
  19423. {
  19424. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  19425. if (constant != NULL)
  19426. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  19427. }
  19428. }
  19429. if (methodDef->mHasComptime)
  19430. methodInstance->mComptimeFlags = BfComptimeFlag_Comptime;
  19431. auto comptimeAttr = customAttributes->Get(mCompiler->mComptimeAttributeTypeDef);
  19432. if (comptimeAttr != NULL)
  19433. {
  19434. for (auto setProp : comptimeAttr->mSetProperties)
  19435. {
  19436. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  19437. if (propertyDef->mName == "OnlyFromComptime")
  19438. {
  19439. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  19440. if ((constant != NULL) && (constant->mBool))
  19441. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_OnlyFromComptime);
  19442. }
  19443. else if (propertyDef->mName == "ConstEval")
  19444. {
  19445. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  19446. if ((constant != NULL) && (constant->mBool))
  19447. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_ConstEval);
  19448. }
  19449. }
  19450. }
  19451. }
  19452. auto delegateInfo = typeInstance->GetDelegateInfo();
  19453. if ((delegateInfo != NULL) && (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) && (methodInstance->mMethodDef->mName == "Invoke"))
  19454. methodInstance->mCallingConvention = delegateInfo->mCallingConvention;
  19455. }
  19456. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  19457. {
  19458. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  19459. {
  19460. // Don't create a func
  19461. return;
  19462. }
  19463. auto typeInstance = methodInstance->GetOwner();
  19464. auto methodDef = methodInstance->mMethodDef;
  19465. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  19466. if (isTemporaryFunc)
  19467. {
  19468. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  19469. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  19470. mangledName = "autocomplete_tmp";
  19471. }
  19472. if (!mBfIRBuilder->mIgnoreWrites)
  19473. {
  19474. BfIRFunction prevFunc;
  19475. // Remove old version (if we have one)
  19476. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  19477. if (prevFunc)
  19478. {
  19479. if ((methodDef->mIsOverride) && (mCurTypeInstance->mTypeDef->mIsCombinedPartial))
  19480. {
  19481. bool takeover = false;
  19482. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  19483. BfMethodDef* nextMethod = NULL;
  19484. BfMemberSetEntry* entry = NULL;
  19485. if (mCurTypeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  19486. nextMethod = (BfMethodDef*)entry->mMemberDef;
  19487. while (nextMethod != NULL)
  19488. {
  19489. auto checkMethod = nextMethod;
  19490. nextMethod = nextMethod->mNextWithSameName;
  19491. if (checkMethod == methodDef)
  19492. continue;
  19493. if (checkMethod->mIsOverride)
  19494. {
  19495. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  19496. if (checkMethodInstance == NULL)
  19497. continue;
  19498. if ((checkMethodInstance->mIRFunction == prevFunc) && (checkMethodInstance->mMethodDef->mMethodDeclaration != NULL))
  19499. {
  19500. BfAstNode* refNode = methodDef->GetRefNode();
  19501. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  19502. refNode = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  19503. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  19504. refNode = methodDeclaration->mVirtualSpecifier;
  19505. auto error = Fail(StrFormat("Conflicting extension override method '%s'", MethodToString(mCurMethodInstance).c_str()), refNode);
  19506. if (error != NULL)
  19507. mCompiler->mPassInstance->MoreInfo("See previous override", checkMethod->GetRefNode());
  19508. takeover = false;
  19509. break;
  19510. }
  19511. }
  19512. if (!checkMethod->mIsExtern)
  19513. continue;
  19514. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  19515. if (checkMethodInstance == NULL)
  19516. continue;
  19517. if (!CompareMethodSignatures(checkMethodInstance, mCurMethodInstance))
  19518. continue;
  19519. // Take over function
  19520. takeover = true;
  19521. }
  19522. if (takeover)
  19523. mCurMethodInstance->mIRFunction = prevFunc;
  19524. if (!mCurMethodInstance->mIRFunction)
  19525. {
  19526. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  19527. if (!mIsComptimeModule)
  19528. mBfIRBuilder->Func_SafeRename(prevFunc);
  19529. }
  19530. }
  19531. else if (methodDef->mIsExtern)
  19532. {
  19533. // Allow this
  19534. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  19535. }
  19536. else if (typeInstance->IsIRFuncUsed(prevFunc))
  19537. {
  19538. // We can have a collision of names when we have generic methods that differ only in
  19539. // their constraints, but they should only collide in their unspecialized form
  19540. // since only one will be chosen for a given concrete type
  19541. if (!mIsComptimeModule)
  19542. mCurMethodInstance->mMangleWithIdx = true;
  19543. mangledName.Clear();
  19544. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  19545. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  19546. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  19547. }
  19548. else
  19549. {
  19550. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  19551. if (!mIsComptimeModule)
  19552. mBfIRBuilder->Func_SafeRename(prevFunc);
  19553. }
  19554. }
  19555. }
  19556. if (typeInstance != mContext->mBfObjectType)
  19557. {
  19558. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  19559. GetMethodCustomAttributes(methodInstance);
  19560. }
  19561. // if (prevFunc)
  19562. // {
  19563. // if (methodDef->mIsExtern)
  19564. // {
  19565. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  19566. // methodInstance->mIRFunction = prevFunc;
  19567. // }
  19568. // else
  19569. // {
  19570. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  19571. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  19572. // {
  19573. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  19574. // BfLogSysM("Ignoring function name collision\n");
  19575. // }
  19576. // else
  19577. // {
  19578. // if (methodDef->mMethodDeclaration == NULL)
  19579. // {
  19580. // AssertErrorState();
  19581. // }
  19582. // else
  19583. // {
  19584. // BF_ASSERT(mIsSpecialModule);
  19585. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  19586. // {
  19587. // // We shouldn't have name collisions on the first run!
  19588. // AssertErrorState();
  19589. // }
  19590. // }
  19591. // }
  19592. // BfLogSysM("Before erase\n");
  19593. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  19594. // }
  19595. // }
  19596. bool isIntrinsic = false;
  19597. if (!methodInstance->mIRFunction)
  19598. {
  19599. BfIRFunction func;
  19600. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType() || (mIsComptimeModule)) &&
  19601. (!methodDef->IsEmptyPartial())) && (funcType);
  19602. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  19603. {
  19604. if (!mIsReified)
  19605. wantsLLVMFunc = false;
  19606. }*/
  19607. if (wantsLLVMFunc)
  19608. {
  19609. func = GetIntrinsic(methodInstance, true);
  19610. if (func)
  19611. {
  19612. isIntrinsic = true;
  19613. }
  19614. else
  19615. {
  19616. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  19617. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  19618. if (methodInstance->mAlwaysInline)
  19619. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  19620. // if (prevFunc)
  19621. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  19622. }
  19623. methodInstance->mIRFunction = func;
  19624. //if (!ignoreWrites)
  19625. //BF_ASSERT(!func.IsFake());
  19626. }
  19627. }
  19628. if (outIsIntrinsic != NULL)
  19629. *outIsIntrinsic = isIntrinsic;
  19630. if (!isIntrinsic)
  19631. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  19632. }
  19633. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  19634. {
  19635. if (methodInstance->mHotMethod != NULL)
  19636. return;
  19637. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  19638. {
  19639. auto srcTypeInst = methodInstance->GetOwner();
  19640. StringT<128> mangledName = inMangledName;
  19641. if (mangledName.IsEmpty())
  19642. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  19643. // We always keep the current primary method at the same address
  19644. BfHotMethod* hotMethod;
  19645. BfHotMethod** hotMethodPtr;
  19646. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  19647. {
  19648. hotMethod = new BfHotMethod();
  19649. *hotMethodPtr = hotMethod;
  19650. hotMethod->mRefCount = 1;
  19651. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  19652. #ifdef BF_DBG_HOTMETHOD_IDX
  19653. static int sMethodIdx = 0;
  19654. hotMethod->mMethodIdx = sMethodIdx++;
  19655. #endif
  19656. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  19657. }
  19658. else
  19659. {
  19660. hotMethod = *hotMethodPtr;
  19661. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  19662. {
  19663. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  19664. auto prevHotMethod = *hotMethodPtr;
  19665. hotMethod = new BfHotMethod();
  19666. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  19667. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  19668. hotDupMethod->mRefCount++;
  19669. prevHotMethod->mReferences.Add(hotDupMethod);
  19670. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  19671. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  19672. }
  19673. else if (mCompiler->IsHotCompile())
  19674. {
  19675. // Link the previous version into the mPrevVersion
  19676. BfHotMethod* prevMethod = new BfHotMethod();
  19677. prevMethod->mRefCount = 1;
  19678. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  19679. hotMethod->mPrevVersion = prevMethod;
  19680. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  19681. hotMethod->mSrcTypeVersion = NULL;
  19682. prevMethod->mFlags = hotMethod->mFlags;
  19683. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  19684. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  19685. #ifdef BF_DBG_HOTMETHOD_NAME
  19686. prevMethod->mMangledName = hotMethod->mMangledName;
  19687. #endif
  19688. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  19689. }
  19690. else
  19691. {
  19692. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  19693. hotMethod->Clear(true);
  19694. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  19695. }
  19696. }
  19697. if (methodInstance->mIsClosure)
  19698. {
  19699. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  19700. }
  19701. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  19702. hotMethod->mSrcTypeVersion->mRefCount++;
  19703. hotMethod->mRefCount++;
  19704. #ifdef BF_DBG_HOTMETHOD_NAME
  19705. hotMethod->mMangledName = mangledName;
  19706. #endif
  19707. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!IsHotCompile()))
  19708. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  19709. methodInstance->mHotMethod = hotMethod;
  19710. }
  19711. }
  19712. static void StackOverflow()
  19713. {
  19714. int i = 0;
  19715. if (i == 0)
  19716. StackOverflow();
  19717. }
  19718. void BfModule::StartMethodDeclaration(BfMethodInstance* methodInstance, BfMethodState* prevMethodState)
  19719. {
  19720. methodInstance->mHasStartedDeclaration = true;
  19721. auto methodDef = methodInstance->mMethodDef;
  19722. auto typeInstance = methodInstance->GetOwner();
  19723. bool hasNonGenericParams = false;
  19724. bool hasGenericParams = false;
  19725. int dependentGenericStartIdx = 0;
  19726. if (methodDef->mIsLocalMethod)
  19727. {
  19728. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  19729. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  19730. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  19731. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  19732. // over the local method each time
  19733. auto rootMethodInstance = prevMethodState->GetRootMethodState()->mMethodInstance;
  19734. dependentGenericStartIdx = 0;
  19735. if (rootMethodInstance != NULL)
  19736. {
  19737. if (rootMethodInstance->mMethodInfoEx != NULL)
  19738. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  19739. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  19740. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  19741. }
  19742. }
  19743. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodInstance->GetNumGenericArguments(); genericArgIdx++)
  19744. {
  19745. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  19746. if (genericArgType->IsGenericParam())
  19747. {
  19748. hasGenericParams = true;
  19749. auto genericParam = (BfGenericParamType*)genericArgType;
  19750. methodInstance->mIsUnspecialized = true;
  19751. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  19752. methodInstance->mIsUnspecializedVariation = true;
  19753. }
  19754. else
  19755. {
  19756. hasNonGenericParams = true;
  19757. if (genericArgType->IsUnspecializedType())
  19758. {
  19759. methodInstance->mIsUnspecialized = true;
  19760. methodInstance->mIsUnspecializedVariation = true;
  19761. }
  19762. }
  19763. }
  19764. if ((hasGenericParams) && (hasNonGenericParams))
  19765. {
  19766. methodInstance->mIsUnspecializedVariation = true;
  19767. }
  19768. if (typeInstance->IsUnspecializedType())
  19769. {
  19770. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  19771. // actually want to do method processing on it
  19772. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  19773. methodInstance->mIsUnspecializedVariation = true;
  19774. methodInstance->mIsUnspecialized = true;
  19775. }
  19776. if (methodInstance->mIsUnspecializedVariation)
  19777. BF_ASSERT(methodInstance->mIsUnspecialized);
  19778. //TODO: Why did we do this?
  19779. if (methodDef->mMethodType == BfMethodType_Mixin)
  19780. {
  19781. if (methodInstance->IsSpecializedGenericMethod())
  19782. methodInstance->mIsUnspecializedVariation = true;
  19783. methodInstance->mIsUnspecialized = true;
  19784. }
  19785. }
  19786. // methodDeclaration is NULL for default constructors
  19787. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  19788. {
  19789. BF_ASSERT((mCompiler->mCeMachine == NULL) || (!mCompiler->mCeMachine->mDbgPaused));
  19790. BP_ZONE("BfModule::DoMethodDeclaration");
  19791. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  19792. // to effectively make mIgnoreWrites method-scoped
  19793. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  19794. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  19795. SetAndRestoreValue<bool> prevAllowLockYield(mContext->mAllowLockYield, false);
  19796. BfTypeState typeState(mCurTypeInstance);
  19797. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  19798. if (mCompiler->IsAutocomplete())
  19799. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  19800. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  19801. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  19802. BfMethodState methodState;
  19803. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  19804. methodState.mTempKind = BfMethodState::TempKind_Static;
  19805. defer({ mCurMethodInstance->mHasBeenDeclared = true; });
  19806. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  19807. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  19808. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  19809. // if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  19810. // {
  19811. // BF_ASSERT(mContext->mResolvingVarField);
  19812. // isTemporaryFunc = true;
  19813. // }
  19814. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  19815. FinishInit();
  19816. auto typeInstance = mCurTypeInstance;
  19817. auto typeDef = typeInstance->mTypeDef;
  19818. auto methodDef = mCurMethodInstance->mMethodDef;
  19819. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  19820. if (methodDef->mName == "__FATALERRORNAME")
  19821. BFMODULE_FATAL(this, "__FATALERRORNAME");
  19822. if (methodDef->mName == "__STACKOVERFLOW")
  19823. StackOverflow();
  19824. if (typeInstance->IsClosure())
  19825. {
  19826. if (methodDef->mName == "Invoke")
  19827. return;
  19828. }
  19829. auto methodInstance = mCurMethodInstance;
  19830. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  19831. addToWorkList = false;
  19832. if (!methodInstance->mHasStartedDeclaration)
  19833. StartMethodDeclaration(methodInstance, prevMethodState.mPrevVal);
  19834. BfAutoComplete* bfAutocomplete = NULL;
  19835. if (mCompiler->mResolvePassData != NULL)
  19836. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  19837. if (methodInstance->mMethodInfoEx != NULL)
  19838. {
  19839. BfTypeInstance* unspecializedTypeInstance = NULL;
  19840. Array<BfTypeReference*> deferredResolveTypes;
  19841. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  19842. {
  19843. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  19844. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  19845. {
  19846. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  19847. }
  19848. else
  19849. {
  19850. auto externConstraintDef = genericParam->GetExternConstraintDef();
  19851. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  19852. auto autoComplete = mCompiler->GetAutoComplete();
  19853. if (autoComplete != NULL)
  19854. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  19855. if (genericParam->mExternType != NULL)
  19856. {
  19857. //
  19858. }
  19859. else
  19860. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  19861. }
  19862. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized, &deferredResolveTypes);
  19863. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  19864. {
  19865. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  19866. if (bfAutocomplete != NULL)
  19867. {
  19868. for (auto nameNode : genericParamDef->mNameNodes)
  19869. {
  19870. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  19871. }
  19872. }
  19873. }
  19874. }
  19875. for (auto typeRef : deferredResolveTypes)
  19876. auto constraintType = ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_None);
  19877. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  19878. AddDependency(genericParam, mCurTypeInstance);
  19879. }
  19880. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  19881. {
  19882. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19883. BfAstNode* nameNode = methodDeclaration->mNameNode;
  19884. if (nameNode == NULL)
  19885. {
  19886. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  19887. nameNode = ctorDeclaration->mThisToken;
  19888. }
  19889. if ((autoComplete->IsAutocompleteNode(nameNode)) && (autoComplete->mResolveType != BfResolveType_Autocomplete))
  19890. {
  19891. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  19892. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  19893. autoComplete->mDefType = typeDef;
  19894. autoComplete->mDefMethod = methodDef;
  19895. autoComplete->SetDefinitionLocation(nameNode);
  19896. if (methodDef->mIsOverride)
  19897. {
  19898. bool found = false;
  19899. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  19900. {
  19901. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  19902. if (ventry.mDeclaringMethod.mMethodNum == -1)
  19903. continue;
  19904. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  19905. if (virtMethod != NULL)
  19906. {
  19907. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  19908. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  19909. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  19910. {
  19911. // Is matching method
  19912. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  19913. {
  19914. auto baseType = typeInstance->mBaseType;
  19915. if (baseType != NULL)
  19916. {
  19917. found = true;
  19918. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  19919. baseType = baseType->mBaseType;
  19920. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  19921. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  19922. autoComplete->mDefType = baseType->mTypeDef;
  19923. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  19924. }
  19925. }
  19926. break;
  19927. }
  19928. }
  19929. }
  19930. if ((!found) && (autoComplete->mIsGetDefinition) && (methodDef->mDeclaringType->IsExtension()))
  19931. {
  19932. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  19933. {
  19934. auto defaultMethod = methodGroup.mDefault;
  19935. if (defaultMethod == NULL)
  19936. continue;
  19937. if (!defaultMethod->mMethodDef->mIsExtern)
  19938. continue;
  19939. if (!CompareMethodSignatures(defaultMethod, methodInstance))
  19940. continue;
  19941. autoComplete->SetDefinitionLocation(defaultMethod->mMethodDef->GetRefNode(), true);
  19942. autoComplete->mDefType = typeInstance->mTypeDef;
  19943. autoComplete->mDefMethod = defaultMethod->mMethodDef;
  19944. }
  19945. }
  19946. }
  19947. }
  19948. }
  19949. bool reportErrors = true;
  19950. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  19951. reportErrors = true;
  19952. // Only the defining contexts needs to report errors here
  19953. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  19954. if (methodDef->mMethodType == BfMethodType_Dtor)
  19955. {
  19956. if (methodDef->mIsStatic)
  19957. {
  19958. }
  19959. else
  19960. {
  19961. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  19962. {
  19963. BfAstNode* refNode = methodDeclaration;
  19964. if (refNode == NULL)
  19965. {
  19966. // Whatever caused this ctor to be generated should have caused another failure
  19967. // But that failure might not be generated until the ctor is generated
  19968. }
  19969. else
  19970. {
  19971. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  19972. if (dtorDecl != NULL)
  19973. refNode = dtorDecl->mThisToken;
  19974. Fail("Structs cannot have destructors", refNode);
  19975. }
  19976. }
  19977. auto methodDeclaration = methodDef->GetMethodDeclaration();
  19978. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  19979. (mCurTypeInstance != mContext->mBfObjectType))
  19980. {
  19981. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  19982. }
  19983. }
  19984. }
  19985. BfType* resolvedReturnType = NULL;
  19986. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  19987. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  19988. (methodDef->mReturnTypeRef != NULL))
  19989. {
  19990. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  19991. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric);
  19992. if ((((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0) || (methodInstance->mIsAutocompleteMethod))
  19993. && (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>()))
  19994. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  19995. else
  19996. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration, flags);
  19997. if (resolvedReturnType == NULL)
  19998. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  19999. if ((methodDef->mIsReadOnly) && (!resolvedReturnType->IsRef()))
  20000. {
  20001. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration))
  20002. if (methodDeclaration->mReadOnlySpecifier != NULL)
  20003. Fail("Readonly specifier is only valid on 'ref' return types", methodDeclaration->mReadOnlySpecifier);
  20004. }
  20005. }
  20006. else
  20007. {
  20008. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  20009. }
  20010. BF_ASSERT(resolvedReturnType != NULL);
  20011. mCurMethodInstance->mReturnType = resolvedReturnType;
  20012. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  20013. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  20014. //if (!methodInstance->IsSpecializedGenericMethod())
  20015. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  20016. if (methodDef->mExplicitInterface != NULL)
  20017. {
  20018. auto autoComplete = mCompiler->GetAutoComplete();
  20019. if (autoComplete != NULL)
  20020. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  20021. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  20022. BfTypeInstance* explicitInterface = NULL;
  20023. if (explicitType != NULL)
  20024. explicitInterface = explicitType->ToTypeInstance();
  20025. if (explicitInterface != NULL)
  20026. {
  20027. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  20028. if (autoComplete != NULL)
  20029. {
  20030. BfTokenNode* dotToken = NULL;
  20031. BfAstNode* nameNode = NULL;
  20032. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  20033. {
  20034. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  20035. nameNode = methodDeclaration->mNameNode;
  20036. }
  20037. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  20038. }
  20039. }
  20040. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  20041. {
  20042. bool interfaceFound = false;
  20043. for (auto ifaceInst : typeInstance->mInterfaces)
  20044. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  20045. if (!interfaceFound)
  20046. {
  20047. if (methodDef->mMethodDeclaration != NULL)
  20048. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  20049. else
  20050. {
  20051. // For property decls, we should have already given the error during type population
  20052. if (mCompiler->mRevision == 1)
  20053. AssertErrorState();
  20054. }
  20055. }
  20056. }
  20057. }
  20058. bool isThisStruct = mCurTypeInstance->IsStruct();
  20059. BfType* thisType = NULL;
  20060. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  20061. {
  20062. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  20063. {
  20064. thisType = mCurTypeInstance;
  20065. if (thisType == NULL)
  20066. return;
  20067. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  20068. {
  20069. BfTypeUtils::SplatIterate([&](BfType* checkType)
  20070. {
  20071. PopulateType(checkType, BfPopulateType_Data);
  20072. }, thisType);
  20073. }
  20074. }
  20075. else
  20076. {
  20077. thisType = mCurTypeInstance;
  20078. PopulateType(thisType, BfPopulateType_Declaration);
  20079. }
  20080. }
  20081. int implicitParamCount = 0;
  20082. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  20083. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  20084. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  20085. bool hadDelegateParams = false;
  20086. bool hadParams = false;
  20087. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  20088. {
  20089. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  20090. BfParameterDef* paramDef = NULL;
  20091. int paramDefIdx = -1;
  20092. if (paramIdx < implicitParamCount)
  20093. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  20094. else
  20095. {
  20096. paramDefIdx = paramIdx - implicitParamCount;
  20097. paramDef = methodDef->mParams[paramDefIdx];
  20098. }
  20099. if (hadParams)
  20100. break;
  20101. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  20102. continue;
  20103. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  20104. (paramDef->mParamKind != BfParamKind_AppendIdx))
  20105. {
  20106. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  20107. if (mCompiler->mResolvePassData->mAutoComplete->IsAutocompleteNode(paramDef->mTypeRef))
  20108. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("token", "in"), paramDef->mTypeRef->ToString());
  20109. }
  20110. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  20111. {
  20112. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20113. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20114. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  20115. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  20116. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  20117. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  20118. }
  20119. BfType* resolvedParamType = NULL;
  20120. if (closureCaptureEntry != NULL)
  20121. resolvedParamType = closureCaptureEntry->mType;
  20122. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfLetTypeReference>()))
  20123. {
  20124. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  20125. resolvedParamType = mContext->mBfObjectType;
  20126. }
  20127. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfVarTypeReference>()))
  20128. {
  20129. if (methodDef->mMethodType != BfMethodType_Mixin)
  20130. {
  20131. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  20132. resolvedParamType = mContext->mBfObjectType;
  20133. }
  20134. else
  20135. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  20136. }
  20137. BfType* unresolvedParamType = resolvedParamType;
  20138. bool wasGenericParam = false;
  20139. if (resolvedParamType == NULL)
  20140. {
  20141. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  20142. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  20143. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  20144. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  20145. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  20146. resolvedParamType = resolvedParamType->GetUnderlyingType();
  20147. }
  20148. if (resolvedParamType == NULL)
  20149. {
  20150. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  20151. unresolvedParamType = resolvedParamType;
  20152. if (mCurTypeInstance->IsBoxed())
  20153. {
  20154. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  20155. // If we failed a lookup here then we better have also failed it in the original type
  20156. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType->ToTypeInstance()));
  20157. }
  20158. }
  20159. if (!methodInstance->IsSpecializedGenericMethod())
  20160. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  20161. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  20162. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  20163. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  20164. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  20165. {
  20166. if (paramDef->mParamKind == BfParamKind_Params)
  20167. {
  20168. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  20169. if (refNode != NULL)
  20170. refNode = paramDef->mParamDeclaration->mModToken;
  20171. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  20172. }
  20173. BfTypedValue defaultValue;
  20174. if (resolvedParamType->IsConstExprValue())
  20175. {
  20176. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  20177. BfExprEvaluator exprEvaluator(this);
  20178. exprEvaluator.mExpectingType = constExprType->mType;
  20179. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  20180. defaultValue = exprEvaluator.GetResult();
  20181. }
  20182. else
  20183. {
  20184. BfTypeState typeState;
  20185. typeState.mType = mCurTypeInstance;
  20186. typeState.mCurTypeDef = methodDef->mDeclaringType;
  20187. //typeState.mCurMethodDef = methodDef;
  20188. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20189. BfConstResolver constResolver(this);
  20190. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  20191. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  20192. {
  20193. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  20194. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  20195. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  20196. {
  20197. defaultValue = castedDefaultValue; // Good!
  20198. }
  20199. else if (!CanCast(defaultValue, resolvedParamType))
  20200. {
  20201. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  20202. // a conversion operator.
  20203. // This should throw an error
  20204. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  20205. AssertErrorState();
  20206. if (!defaultValue.mValue.IsConst())
  20207. defaultValue = BfTypedValue();
  20208. }
  20209. }
  20210. }
  20211. if (!defaultValue)
  20212. {
  20213. defaultValue = GetDefaultTypedValue(resolvedParamType);
  20214. if (!defaultValue.mValue.IsConst())
  20215. defaultValue = BfTypedValue();
  20216. }
  20217. if (defaultValue)
  20218. {
  20219. if (defaultValue.mType->IsVar())
  20220. {
  20221. AssertErrorState();
  20222. }
  20223. else
  20224. {
  20225. BF_ASSERT(defaultValue.mValue.IsConst());
  20226. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  20227. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  20228. CurrentAddToConstHolder(defaultValue.mValue);
  20229. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  20230. }
  20231. }
  20232. }
  20233. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  20234. {
  20235. bool addParams = true;
  20236. bool isValid = false;
  20237. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  20238. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->IsInstanceOf(mCompiler->mSpanTypeDef)))
  20239. {
  20240. // Span<T>
  20241. isValid = true;
  20242. }
  20243. else if (resolvedParamType->IsArray())
  20244. {
  20245. // Array is the 'normal' params type
  20246. isValid = true;
  20247. }
  20248. else if (resolvedParamType->IsSizedArray())
  20249. {
  20250. isValid = true;
  20251. }
  20252. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  20253. {
  20254. hadDelegateParams = true;
  20255. // This means we copy the params from a delegate
  20256. BfMethodParam methodParam;
  20257. methodParam.mResolvedType = resolvedParamType;
  20258. methodParam.mParamDefIdx = paramDefIdx;
  20259. methodParam.mDelegateParamIdx = 0;
  20260. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  20261. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  20262. {
  20263. methodParam.mDelegateParamIdx = delegateParamIdx;
  20264. mCurMethodInstance->mParams.Add(methodParam);
  20265. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  20266. if (!methodInstance->IsSpecializedGenericMethod())
  20267. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  20268. }
  20269. isValid = true;
  20270. addParams = false;
  20271. }
  20272. else if (resolvedParamType->IsGenericParam())
  20273. {
  20274. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  20275. if (genericParamInstance->mTypeConstraint != NULL)
  20276. {
  20277. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  20278. if ((genericParamInstance->mTypeConstraint->IsArray()) || (genericParamInstance->mTypeConstraint->IsSizedArray()))
  20279. {
  20280. BfMethodParam methodParam;
  20281. methodParam.mResolvedType = resolvedParamType;
  20282. methodParam.mParamDefIdx = paramDefIdx;
  20283. mCurMethodInstance->mParams.Add(methodParam);
  20284. isValid = true;
  20285. }
  20286. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  20287. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  20288. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  20289. {
  20290. mCurMethodInstance->mHadGenericDelegateParams = true;
  20291. isValid = true;
  20292. addParams = false;
  20293. }
  20294. }
  20295. }
  20296. else
  20297. {
  20298. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  20299. if ((paramTypeInst != NULL) &&
  20300. ((paramTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef))))
  20301. {
  20302. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  20303. isValid = true;
  20304. addParams = false;
  20305. }
  20306. }
  20307. if (!isValid)
  20308. {
  20309. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  20310. // Failure case, make it an Object[]
  20311. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  20312. }
  20313. if ((addParams) && (resolvedParamType != NULL))
  20314. {
  20315. BfMethodParam methodParam;
  20316. methodParam.mResolvedType = resolvedParamType;
  20317. methodParam.mParamDefIdx = paramDefIdx;
  20318. mCurMethodInstance->mParams.push_back(methodParam);
  20319. }
  20320. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  20321. {
  20322. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  20323. }
  20324. }
  20325. else
  20326. {
  20327. BfMethodParam methodParam;
  20328. methodParam.mResolvedType = resolvedParamType;
  20329. methodParam.mParamDefIdx = paramDefIdx;
  20330. mCurMethodInstance->mParams.Add(methodParam);
  20331. }
  20332. }
  20333. if (hadDelegateParams)
  20334. {
  20335. HashSet<String> usedNames;
  20336. Dictionary<int, int> usedParamDefIdx;
  20337. for (auto methodParam : methodDef->mParams)
  20338. {
  20339. usedNames.Add(methodParam->mName);
  20340. }
  20341. for (auto& methodParam : mCurMethodInstance->mParams)
  20342. {
  20343. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  20344. {
  20345. int* refCount = NULL;
  20346. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  20347. (*refCount)++;
  20348. }
  20349. }
  20350. for (auto& methodParam : mCurMethodInstance->mParams)
  20351. {
  20352. if (methodParam.mDelegateParamIdx != -1)
  20353. {
  20354. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  20355. methodParam.mDelegateParamNameCombine = true;
  20356. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  20357. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  20358. if (usedNames.Contains(paramName))
  20359. methodParam.mDelegateParamNameCombine = true;
  20360. }
  20361. }
  20362. }
  20363. int argIdx = 0;
  20364. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  20365. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  20366. {
  20367. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  20368. auto thisType = methodInstance->GetOwner();
  20369. if (methodInstance->GetParamIsSplat(thisIdx))
  20370. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  20371. else if (!thisType->IsValuelessType())
  20372. {
  20373. BfTypeCode loweredTypeCode = BfTypeCode_None;
  20374. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  20375. if ((!mIsComptimeModule) && (!methodDef->mIsMutating))
  20376. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  20377. argIdx++;
  20378. if (loweredTypeCode2 != BfTypeCode_None)
  20379. argIdx++;
  20380. }
  20381. }
  20382. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  20383. argIdx++;
  20384. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  20385. {
  20386. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  20387. BfType* checkType = methodParam.mResolvedType;
  20388. int checkArgIdx = argIdx;
  20389. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  20390. {
  20391. checkArgIdx = 0;
  20392. checkType = methodInstance->GetThisType();
  20393. }
  20394. if (checkType->IsMethodRef())
  20395. {
  20396. methodParam.mIsSplat = true;
  20397. }
  20398. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting(paramIdx)))
  20399. {
  20400. PopulateType(checkType, BfPopulateType_Data);
  20401. if (checkType->IsSplattable())
  20402. {
  20403. bool isSplat = false;
  20404. auto checkTypeInstance = checkType->ToTypeInstance();
  20405. if ((checkTypeInstance != NULL) && (checkTypeInstance->mIsCRepr))
  20406. isSplat = true;
  20407. int splatCount = checkType->GetSplatCount();
  20408. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  20409. isSplat = true;
  20410. if (isSplat)
  20411. {
  20412. methodParam.mIsSplat = true;
  20413. argIdx += splatCount;
  20414. continue;
  20415. }
  20416. }
  20417. else if (!checkType->IsValuelessType())
  20418. {
  20419. BfTypeCode loweredTypeCode = BfTypeCode_None;
  20420. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  20421. if (!mIsComptimeModule)
  20422. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  20423. argIdx++;
  20424. if (loweredTypeCode2 != BfTypeCode_None)
  20425. argIdx++;
  20426. continue;
  20427. }
  20428. }
  20429. argIdx++;
  20430. }
  20431. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  20432. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  20433. {
  20434. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  20435. }
  20436. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  20437. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  20438. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  20439. (!methodDef->mIsSkipCall))
  20440. {
  20441. if (methodDeclaration->mEndSemicolon == NULL)
  20442. {
  20443. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  20444. {
  20445. //
  20446. }
  20447. else
  20448. AssertParseErrorState();
  20449. }
  20450. else
  20451. {
  20452. bool isError = true;
  20453. if (typeInstance->IsTypedPrimitive())
  20454. {
  20455. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  20456. {
  20457. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  20458. {
  20459. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  20460. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  20461. {
  20462. isError = false;
  20463. }
  20464. }
  20465. }
  20466. }
  20467. if (isError)
  20468. {
  20469. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  20470. MethodToString(methodInstance).c_str()),
  20471. methodDef->GetRefNode());
  20472. }
  20473. }
  20474. }
  20475. if (methodDef->IsEmptyPartial())
  20476. hasExternSpecifier = true;
  20477. if (!methodInstance->IsAutocompleteMethod())
  20478. {
  20479. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  20480. int implicitParamCount = methodInstance->GetImplicitParamCount();
  20481. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  20482. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  20483. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  20484. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  20485. int paramIdx = 0;
  20486. int defaultParamIdx = 0;
  20487. while (true)
  20488. {
  20489. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  20490. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  20491. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  20492. {
  20493. paramIdx++;
  20494. continue;
  20495. }
  20496. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  20497. {
  20498. defaultParamIdx++;
  20499. continue;
  20500. }
  20501. if ((isDone) || (isDefaultDone))
  20502. {
  20503. // 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
  20504. // to cause us to throw an assertion in the declaration here
  20505. if (!defaultMethodInstance->mHadGenericDelegateParams)
  20506. BF_ASSERT((isDone) && (isDefaultDone));
  20507. break;
  20508. }
  20509. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  20510. if (paramType->IsRef())
  20511. paramType = paramType->GetUnderlyingType();
  20512. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  20513. paramIdx++;
  20514. defaultParamIdx++;
  20515. }
  20516. }
  20517. StringT<128> mangledName;
  20518. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  20519. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  20520. {
  20521. auto paramType = methodInstance->GetParamType(paramIdx);
  20522. if (paramType->IsComposite())
  20523. PopulateType(paramType, BfPopulateType_Data);
  20524. if (!methodInstance->IsParamSkipped(paramIdx))
  20525. {
  20526. if (paramType->IsStruct())
  20527. {
  20528. //
  20529. }
  20530. else
  20531. {
  20532. PopulateType(paramType, BfPopulateType_Declaration);
  20533. }
  20534. }
  20535. }
  20536. // Only process method in default unspecialized mode, not in variations
  20537. if (methodInstance->mIsUnspecializedVariation)
  20538. return;
  20539. PopulateType(resolvedReturnType, BfPopulateType_Data);
  20540. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  20541. if (resolvedReturnType->IsValuelessType())
  20542. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  20543. if (!mBfIRBuilder->mIgnoreWrites)
  20544. {
  20545. bool isIntrinsic = false;
  20546. if (!methodInstance->mIRFunction)
  20547. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  20548. if (isIntrinsic)
  20549. {
  20550. addToWorkList = false;
  20551. }
  20552. }
  20553. auto func = methodInstance->mIRFunction;
  20554. // if (methodInstance->mIsReified)
  20555. // CheckHotMethod(methodInstance, mangledName);
  20556. 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);
  20557. SizedArray<BfIRMDNode, 8> diParams;
  20558. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  20559. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  20560. {
  20561. //CS0708
  20562. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  20563. }
  20564. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  20565. {
  20566. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  20567. methodDef->mIsVirtual = false;
  20568. }
  20569. BfAstNode* mutSpecifier = NULL;
  20570. if (methodDeclaration != NULL)
  20571. mutSpecifier = methodDeclaration->mMutSpecifier;
  20572. else if (methodDef->GetPropertyMethodDeclaration() != NULL)
  20573. {
  20574. mutSpecifier = methodDef->GetPropertyMethodDeclaration()->mMutSpecifier;
  20575. if (mutSpecifier == NULL)
  20576. {
  20577. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  20578. if (propertyDeclaration != NULL)
  20579. {
  20580. if (auto propExprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  20581. mutSpecifier = propExprBody->mMutSpecifier;
  20582. }
  20583. }
  20584. }
  20585. if ((mutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  20586. {
  20587. if (methodDef->mIsStatic)
  20588. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", mutSpecifier);
  20589. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  20590. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", mutSpecifier);
  20591. else if (methodDef->mMethodType == BfMethodType_Ctor)
  20592. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", mutSpecifier);
  20593. else if (methodDef->mMethodType == BfMethodType_Dtor)
  20594. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", mutSpecifier);
  20595. }
  20596. if (isTemporaryFunc)
  20597. {
  20598. // This handles temporary methods for autocomplete types
  20599. //BF_ASSERT(mIsScratchModule);
  20600. //BF_ASSERT(mCompiler->IsAutocomplete());
  20601. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  20602. return; // Bail out early for autocomplete pass
  20603. }
  20604. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  20605. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  20606. // autocompleter. Why did we have this check anyway?
  20607. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  20608. {
  20609. AddMethodReference(methodInstance);
  20610. mFuncReferences[methodInstance] = func;
  20611. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  20612. }*/
  20613. if (mParentModule != NULL)
  20614. {
  20615. // For extension modules we need to keep track of our own methods so we can know which methods
  20616. // we have defined ourselves and which are from the parent module or other extensions
  20617. if (!func.IsFake())
  20618. {
  20619. if (func)
  20620. mFuncReferences[methodInstance] = func;
  20621. }
  20622. }
  20623. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  20624. {
  20625. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  20626. auto owningModule = methodInstance->GetOwner()->mModule;
  20627. if (!owningModule->mIsScratchModule)
  20628. owningModule->mOnDemandMethodCount++;
  20629. VerifyOnDemandMethods();
  20630. }
  20631. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  20632. if (wasAwaitingDecl)
  20633. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  20634. if (addToWorkList)
  20635. {
  20636. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  20637. {
  20638. AddMethodToWorkList(methodInstance);
  20639. }
  20640. else
  20641. {
  20642. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  20643. methodInstance->mIgnoreBody = true;
  20644. if (typeInstance->IsUnspecializedType())
  20645. {
  20646. // Don't hold on to actual Function for unspecialized types
  20647. methodInstance->mIRFunction = BfIRFunction();
  20648. }
  20649. }
  20650. }
  20651. else
  20652. {
  20653. //BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  20654. }
  20655. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  20656. (!methodDef->mIsLocalMethod) &&
  20657. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  20658. (!methodDef->mReturnTypeRef->IsTemporary()))
  20659. {
  20660. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  20661. {
  20662. //TODO:
  20663. //CS0053
  20664. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  20665. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  20666. methodDef->mReturnTypeRef, true);
  20667. }
  20668. else
  20669. {
  20670. //CS0050
  20671. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  20672. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  20673. methodDef->mReturnTypeRef, true);
  20674. }
  20675. }
  20676. if (typeInstance->IsInterface())
  20677. {
  20678. if (methodDef->mMethodType == BfMethodType_Ctor)
  20679. Fail("Interfaces cannot contain constructors", methodDeclaration);
  20680. if (methodDeclaration != NULL)
  20681. {
  20682. if (methodDef->mBody == NULL)
  20683. {
  20684. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  20685. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  20686. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  20687. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  20688. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  20689. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  20690. }
  20691. }
  20692. }
  20693. bool foundHiddenMethod = false;
  20694. BfTokenNode* virtualToken = NULL;
  20695. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  20696. if (propertyDeclaration != NULL)
  20697. virtualToken = propertyDeclaration->mVirtualSpecifier;
  20698. else if (methodDeclaration != NULL)
  20699. virtualToken = methodDeclaration->mVirtualSpecifier;
  20700. // Don't compare specialized generic methods against normal methods
  20701. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  20702. (!methodDef->mIsLocalMethod) && (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  20703. {
  20704. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  20705. {
  20706. typeDef->PopulateMemberSets();
  20707. BfMethodDef* nextMethod = NULL;
  20708. BfMemberSetEntry* entry = NULL;
  20709. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  20710. nextMethod = (BfMethodDef*)entry->mMemberDef;
  20711. while (nextMethod != NULL)
  20712. {
  20713. auto checkMethod = nextMethod;
  20714. nextMethod = nextMethod->mNextWithSameName;
  20715. if (checkMethod == methodDef)
  20716. continue;
  20717. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20718. if (checkMethodInstance == NULL)
  20719. {
  20720. if ((methodDef->mIsNew) && (methodDef->mDeclaringType->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension()))
  20721. checkMethodInstance = GetRawMethodInstanceAtIdx(typeInstance, checkMethod->mIdx);
  20722. if (checkMethodInstance == NULL)
  20723. continue;
  20724. }
  20725. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  20726. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  20727. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  20728. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  20729. {
  20730. bool canChain = false;
  20731. if ((methodDef->mParams.empty()) &&
  20732. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  20733. {
  20734. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  20735. canChain = true;
  20736. else if (methodDef->mMethodType == BfMethodType_Normal)
  20737. {
  20738. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  20739. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  20740. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  20741. canChain = true;
  20742. }
  20743. }
  20744. if (canChain)
  20745. {
  20746. bool isBetter;
  20747. bool isWorse;
  20748. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  20749. if (isBetter && !isWorse)
  20750. {
  20751. methodInstance->mChainType = BfMethodChainType_ChainHead;
  20752. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  20753. }
  20754. else
  20755. {
  20756. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  20757. methodInstance->mChainType = BfMethodChainType_ChainMember;
  20758. }
  20759. }
  20760. else
  20761. {
  20762. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  20763. continue;
  20764. bool silentlyAllow = false;
  20765. bool extensionWarn = false;
  20766. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  20767. {
  20768. if (typeInstance->IsInterface())
  20769. {
  20770. if (methodDef->mIsOverride)
  20771. silentlyAllow = true;
  20772. }
  20773. else
  20774. {
  20775. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  20776. {
  20777. silentlyAllow = true;
  20778. methodInstance->mIsInnerOverride = true;
  20779. CheckOverridenMethod(methodInstance, checkMethodInstance);
  20780. }
  20781. else if ((methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject) &&
  20782. (!checkMethod->mDeclaringType->IsExtension()))
  20783. {
  20784. foundHiddenMethod = true;
  20785. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  20786. silentlyAllow = true;
  20787. else if (methodDef->mIsNew)
  20788. {
  20789. silentlyAllow = true;
  20790. }
  20791. else
  20792. extensionWarn = true;
  20793. }
  20794. else
  20795. silentlyAllow = true;
  20796. }
  20797. }
  20798. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  20799. silentlyAllow = true;
  20800. if (!silentlyAllow)
  20801. {
  20802. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  20803. {
  20804. auto refNode = methodDef->GetRefNode();
  20805. BfError* bfError;
  20806. if (extensionWarn)
  20807. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  20808. 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'.",
  20809. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  20810. else
  20811. {
  20812. bfError = Fail(StrFormat("Method '%s' already declared with the same parameter types", MethodToString(checkMethodInstance).c_str()), refNode, true);
  20813. }
  20814. if ((bfError != NULL) && (checkMethod->GetRefNode() != refNode))
  20815. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  20816. }
  20817. }
  20818. }
  20819. }
  20820. }
  20821. }
  20822. // Virtual methods give their error while slotting
  20823. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  20824. (!methodDef->mIsLocalMethod) &&
  20825. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  20826. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  20827. {
  20828. auto baseType = typeInstance->mBaseType;
  20829. while (baseType != NULL)
  20830. {
  20831. auto baseTypeDef = baseType->mTypeDef;
  20832. baseTypeDef->PopulateMemberSets();
  20833. BfMethodDef* checkMethod = NULL;
  20834. BfMemberSetEntry* entry = NULL;
  20835. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  20836. checkMethod = (BfMethodDef*)entry->mMemberDef;
  20837. while (checkMethod != NULL)
  20838. {
  20839. if (checkMethod->mMethodDeclaration == NULL)
  20840. {
  20841. checkMethod = checkMethod->mNextWithSameName;
  20842. continue;
  20843. }
  20844. if (baseType->mMethodInstanceGroups.size() == 0)
  20845. {
  20846. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  20847. break;
  20848. }
  20849. if (checkMethod == methodDef)
  20850. {
  20851. checkMethod = checkMethod->mNextWithSameName;
  20852. continue;
  20853. }
  20854. if (checkMethod->mName != methodDef->mName)
  20855. {
  20856. checkMethod = checkMethod->mNextWithSameName;
  20857. continue;
  20858. }
  20859. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  20860. if (checkMethodInstance != NULL)
  20861. {
  20862. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  20863. (checkMethod->mProtection != BfProtection_Private) &&
  20864. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  20865. {
  20866. if (!methodDef->mIsNew)
  20867. {
  20868. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  20869. if (refNode != NULL)
  20870. {
  20871. 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?
  20872. if (bfError != NULL)
  20873. bfError->mIsPersistent = true;
  20874. }
  20875. }
  20876. foundHiddenMethod = true;
  20877. break;
  20878. }
  20879. }
  20880. checkMethod = checkMethod->mNextWithSameName;
  20881. }
  20882. if (foundHiddenMethod)
  20883. break;
  20884. baseType = baseType->mBaseType;
  20885. }
  20886. if ((methodDef->mIsNew) && (!foundHiddenMethod) && (!mCurTypeInstance->IsSpecializedType()))
  20887. {
  20888. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  20889. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  20890. methodDeclaration->mNewSpecifier;
  20891. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  20892. }
  20893. }
  20894. }
  20895. if ((methodDef->mIsConcrete) && (!methodInstance->mIsForeignMethodDef) && (!mCurTypeInstance->IsInterface()))
  20896. {
  20897. Fail("Only interfaces methods can be declared as 'concrete'", methodDeclaration->mVirtualSpecifier);
  20898. }
  20899. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic) && (!methodInstance->mIsInnerOverride))
  20900. {
  20901. if ((virtualToken != NULL) && (virtualToken->mToken == BfToken_Override) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  20902. Fail("No suitable method found to override", virtualToken, true);
  20903. else
  20904. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  20905. }
  20906. else if (methodDef->mIsVirtual)
  20907. {
  20908. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  20909. Fail("Virtual or abstract members cannot be 'private'", virtualToken, true);
  20910. if ((methodDef->mProtection == BfProtection_Internal) && (virtualToken != NULL))
  20911. Fail("Virtual or abstract members cannot be 'internal'. Consider using the 'protected internal' access specifier.", virtualToken, true);
  20912. }
  20913. mCompiler->mStats.mMethodDeclarations++;
  20914. mCompiler->UpdateCompletion();
  20915. }
  20916. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  20917. {
  20918. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  20919. auto typeInstance = mCurTypeInstance;
  20920. auto methodDef = methodInstance->mMethodDef;
  20921. int virtualMethodMatchIdx = -1;
  20922. if (typeInstance->mHotTypeData != NULL)
  20923. {
  20924. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  20925. {
  20926. BF_ASSERT(mCompiler->IsHotCompile());
  20927. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  20928. // may slot this override anyway (?)
  20929. int vTableStart = 0;
  20930. auto implBaseType = typeInstance->GetImplBaseType();
  20931. if (implBaseType != NULL)
  20932. vTableStart = implBaseType->mVirtualMethodTableSize;
  20933. StringT<128> mangledName;
  20934. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  20935. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  20936. {
  20937. // O(1) checking when virtual methods haven't changed
  20938. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  20939. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  20940. if (mangledName == entry.mFuncName)
  20941. {
  20942. virtualMethodMatchIdx = vTableStart + checkIdx;
  20943. break;
  20944. }
  20945. }
  20946. if (virtualMethodMatchIdx != -1)
  20947. {
  20948. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  20949. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  20950. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  20951. }
  20952. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  20953. }
  20954. }
  20955. if (virtualMethodMatchIdx == -1)
  20956. {
  20957. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  20958. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  20959. typeInstance->mVirtualMethodTable.push_back(entry);
  20960. }
  20961. }
  20962. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  20963. {
  20964. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  20965. {
  20966. // When we provide an extension override in the same project a root type override
  20967. isBetter = true;
  20968. isWorse = false;
  20969. }
  20970. else
  20971. {
  20972. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  20973. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  20974. }
  20975. }
  20976. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  20977. {
  20978. BP_ZONE("BfModule::SlotVirtualMethod");
  20979. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  20980. return false;
  20981. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  20982. {
  20983. if (!mCompiler->mOptions.mAllowHotSwapping)
  20984. return;
  20985. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  20986. return;
  20987. if (methodInstance->mHotMethod == NULL)
  20988. CheckHotMethod(methodInstance, "");
  20989. if (methodInstance->mHotMethod == NULL)
  20990. return;
  20991. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  20992. if (declMethodInstance->mHotMethod == NULL)
  20993. CheckHotMethod(declMethodInstance, "");
  20994. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  20995. virtualDecl->mRefCount++;
  20996. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  20997. };
  20998. auto typeInstance = mCurTypeInstance;
  20999. auto typeDef = typeInstance->mTypeDef;
  21000. auto methodDef = methodInstance->mMethodDef;
  21001. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21002. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21003. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  21004. if (methodInstance->mIsInnerOverride)
  21005. return false;
  21006. BfAstNode* declaringNode = methodDeclaration;
  21007. if (propertyMethodDeclaration != NULL)
  21008. declaringNode = propertyMethodDeclaration->mNameNode;
  21009. BfMethodInstance* methodOverriden = NULL;
  21010. bool usedMethod = false;
  21011. BfTokenNode* virtualToken = NULL;
  21012. if (propertyDeclaration != NULL)
  21013. virtualToken = propertyDeclaration->mVirtualSpecifier;
  21014. else if (methodDeclaration != NULL)
  21015. virtualToken = methodDeclaration->mVirtualSpecifier;
  21016. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  21017. {
  21018. //Fail: Static members cannot be marked as override, virtual, or abstract
  21019. }
  21020. else if (methodDef->mIsVirtual)
  21021. {
  21022. if (IsHotCompile())
  21023. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  21024. BfTypeInstance* checkBase = typeInstance;
  21025. // If we are in an extension, look in ourselves first
  21026. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  21027. checkBase = checkBase->mBaseType;
  21028. if (typeInstance->IsValueType())
  21029. {
  21030. if (typeInstance->mBaseType == NULL)
  21031. return false; // It's actually ValueType
  21032. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  21033. if (!methodDef->mIsOverride)
  21034. {
  21035. Fail("Structs cannot have virtual methods", virtualToken, true);
  21036. return false;
  21037. }
  21038. checkBase = mContext->mBfObjectType;
  21039. if (checkBase->mVirtualMethodTableSize == 0)
  21040. PopulateType(checkBase, BfPopulateType_Full);
  21041. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  21042. return false; // System circular ref, don't do struct checking on those
  21043. }
  21044. int virtualMethodMatchIdx = -1;
  21045. bool hadHidingError = false;
  21046. BfMethodInstance* bestOverrideMethodInstance = NULL;
  21047. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  21048. int bestOverrideMethodIdx = -1;
  21049. int ambiguousOverrideMethodIdx = -1;
  21050. if (checkBase != NULL)
  21051. {
  21052. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  21053. auto lookupType = checkBase;
  21054. while (lookupType != NULL)
  21055. {
  21056. lookupType->mTypeDef->PopulateMemberSets();
  21057. BfMethodDef* nextMethodDef = NULL;
  21058. BfMemberSetEntry* entry;
  21059. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  21060. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  21061. while (nextMethodDef != NULL)
  21062. {
  21063. auto checkMethodDef = nextMethodDef;
  21064. nextMethodDef = nextMethodDef->mNextWithSameName;
  21065. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  21066. continue;
  21067. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  21068. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  21069. continue;
  21070. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  21071. if (checkMethodIdx >= baseVirtualMethodTable.mSize)
  21072. FatalError("SlotVirtualMethod OOB in baseVirtualMethodTable[checkMethodIdx]");
  21073. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  21074. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  21075. {
  21076. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  21077. continue;
  21078. }
  21079. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21080. if (baseMethodInstance == NULL)
  21081. {
  21082. AssertErrorState();
  21083. continue;
  21084. }
  21085. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  21086. {
  21087. if (methodDef->mIsOverride)
  21088. {
  21089. BfMethodInstance* checkMethodInstance;
  21090. if (typeInstance->IsValueType())
  21091. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21092. else
  21093. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21094. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  21095. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  21096. continue;
  21097. if (bestOverrideMethodInstance != NULL)
  21098. {
  21099. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  21100. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  21101. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  21102. if (isBetter == isWorse)
  21103. {
  21104. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  21105. }
  21106. else
  21107. {
  21108. if (isWorse)
  21109. continue;
  21110. ambiguousOverrideMethodInstance = NULL;
  21111. }
  21112. }
  21113. bestOverrideMethodInstance = checkMethodInstance;
  21114. bestOverrideMethodIdx = checkMethodIdx;
  21115. }
  21116. else
  21117. {
  21118. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  21119. {
  21120. if (!hadHidingError)
  21121. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  21122. hadHidingError = true;
  21123. }
  21124. }
  21125. }
  21126. }
  21127. lookupType = lookupType->mBaseType;
  21128. }
  21129. }
  21130. //TODO:
  21131. if ((checkBase != NULL)
  21132. && (false)
  21133. )
  21134. {
  21135. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  21136. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  21137. {
  21138. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  21139. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  21140. {
  21141. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  21142. continue;
  21143. }
  21144. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21145. if (baseMethodInstance == NULL)
  21146. {
  21147. AssertErrorState();
  21148. continue;
  21149. }
  21150. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  21151. {
  21152. if (methodDef->mIsOverride)
  21153. {
  21154. BfMethodInstance* checkMethodInstance;
  21155. if (typeInstance->IsValueType())
  21156. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21157. else
  21158. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21159. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  21160. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  21161. continue;
  21162. if (bestOverrideMethodInstance != NULL)
  21163. {
  21164. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  21165. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  21166. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  21167. if (isBetter == isWorse)
  21168. {
  21169. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  21170. }
  21171. else
  21172. {
  21173. if (isWorse)
  21174. continue;
  21175. ambiguousOverrideMethodInstance = NULL;
  21176. }
  21177. }
  21178. bestOverrideMethodInstance = checkMethodInstance;
  21179. bestOverrideMethodIdx = checkMethodIdx;
  21180. }
  21181. else
  21182. {
  21183. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  21184. {
  21185. if (!hadHidingError)
  21186. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  21187. hadHidingError = true;
  21188. }
  21189. }
  21190. }
  21191. }
  21192. }
  21193. if (bestOverrideMethodInstance != NULL)
  21194. {
  21195. if (ambiguousOverrideMethodInstance != NULL)
  21196. {
  21197. bool allow = false;
  21198. // 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.
  21199. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  21200. bool canSeeEachOther = false;
  21201. //
  21202. {
  21203. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  21204. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  21205. canSeeEachOther = true;
  21206. }
  21207. //
  21208. {
  21209. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  21210. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  21211. canSeeEachOther = true;
  21212. }
  21213. if (!canSeeEachOther)
  21214. {
  21215. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  21216. }
  21217. else
  21218. {
  21219. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  21220. if (error != NULL)
  21221. {
  21222. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  21223. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  21224. }
  21225. }
  21226. }
  21227. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  21228. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  21229. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  21230. {
  21231. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  21232. {
  21233. BfTypeReference* returnTypeRef;
  21234. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  21235. {
  21236. returnTypeRef = propertyDeclaration->mTypeRef;
  21237. Fail("Property differs from overridden property by type", returnTypeRef, true);
  21238. }
  21239. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21240. {
  21241. returnTypeRef = methodDeclaration->mReturnType;
  21242. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  21243. }
  21244. else
  21245. {
  21246. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  21247. }
  21248. return usedMethod;
  21249. }
  21250. }
  21251. if (methodDef->mIsOverride)
  21252. {
  21253. // We can have multiple matches when a virtual method is used to implement interface methods
  21254. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  21255. // vtable entries for this method signature
  21256. virtualMethodMatchIdx = bestOverrideMethodIdx;
  21257. if (!typeInstance->IsValueType())
  21258. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21259. if (typeInstance->IsValueType())
  21260. {
  21261. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  21262. }
  21263. else
  21264. {
  21265. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21266. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  21267. BfMethodInstance* setMethodInstance = methodInstance;
  21268. bool doOverride = false;
  21269. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  21270. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  21271. {
  21272. methodOverriden = overridenRef;
  21273. doOverride = true;
  21274. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  21275. {
  21276. bool isBetter = false;
  21277. bool isWorse = false;
  21278. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  21279. if (isBetter == isWorse)
  21280. {
  21281. // We have to resolve later per-project
  21282. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  21283. {
  21284. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  21285. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  21286. }
  21287. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  21288. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  21289. doOverride = false;
  21290. }
  21291. else
  21292. {
  21293. if ((isBetter) && (ambiguityContext != NULL))
  21294. {
  21295. ambiguityContext->Remove(virtualMethodMatchIdx);
  21296. }
  21297. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  21298. {
  21299. if (preferRootDefinition)
  21300. {
  21301. // Leave the master GCMarkMember
  21302. isBetter = false;
  21303. isWorse = true;
  21304. }
  21305. }
  21306. doOverride = isBetter;
  21307. }
  21308. }
  21309. }
  21310. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  21311. {
  21312. methodOverriden = overridenRef;
  21313. doOverride = true;
  21314. }
  21315. if (doOverride)
  21316. {
  21317. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  21318. _AddVirtualDecl(declMethodInstance);
  21319. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21320. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  21321. }
  21322. }
  21323. if (methodOverriden != NULL)
  21324. {
  21325. CheckOverridenMethod(methodInstance, methodOverriden);
  21326. }
  21327. }
  21328. }
  21329. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  21330. {
  21331. if (methodDef->mIsOverride)
  21332. {
  21333. BfTokenNode* overrideToken = NULL;
  21334. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  21335. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  21336. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21337. overrideToken = methodDeclaration->mVirtualSpecifier;
  21338. if (overrideToken != NULL)
  21339. {
  21340. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  21341. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  21342. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  21343. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  21344. else
  21345. Fail("No suitable method found to override", overrideToken, true);
  21346. }
  21347. return usedMethod;
  21348. }
  21349. UniqueSlotVirtualMethod(methodInstance);
  21350. }
  21351. else
  21352. usedMethod = true;
  21353. if (typeInstance->IsValueType())
  21354. return usedMethod;
  21355. }
  21356. bool foundInterface = false;
  21357. bool hadAnyMatch = false;
  21358. // See if this method matches interfaces
  21359. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  21360. {
  21361. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  21362. if (ifaceInst->IsIncomplete())
  21363. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  21364. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  21365. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  21366. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  21367. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  21368. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  21369. continue;
  21370. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  21371. continue;
  21372. bool hadMatch = false;
  21373. BfMethodInstance* hadNameMatch = NULL;
  21374. BfType* expectedReturnType = NULL;
  21375. bool showedError = false;
  21376. // We go through our VTable looking for NULL entries within the interface sections
  21377. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  21378. // because a normal method declared in this type could have matched earlier
  21379. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  21380. ifaceInst->mTypeDef->PopulateMemberSets();
  21381. BfMethodDef* checkMethodDef = NULL;
  21382. BfMemberSetEntry* entry;
  21383. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  21384. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  21385. while (checkMethodDef != NULL)
  21386. {
  21387. int iMethodIdx = checkMethodDef->mIdx;
  21388. int iTableIdx = iMethodIdx + startIdx;
  21389. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  21390. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  21391. bool storeIFaceMethod = false;
  21392. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  21393. {
  21394. checkMethodDef = checkMethodDef->mNextWithSameName;
  21395. continue;
  21396. }
  21397. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  21398. auto iMethodInst = iMethodGroup.mDefault;
  21399. if (iMethodInst == NULL)
  21400. {
  21401. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  21402. AssertErrorState();
  21403. checkMethodDef = checkMethodDef->mNextWithSameName;
  21404. continue;
  21405. }
  21406. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  21407. hadNameMatch = iMethodInst;
  21408. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  21409. if ((!doesMethodSignatureMatch) && (interfaceMethodEntry->mMethodRef.IsNull()))
  21410. {
  21411. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  21412. }
  21413. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  21414. {
  21415. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  21416. {
  21417. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  21418. {
  21419. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  21420. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  21421. if (error != NULL)
  21422. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  21423. showedError = true;
  21424. }
  21425. }
  21426. }
  21427. if (doesMethodSignatureMatch)
  21428. {
  21429. usedMethod = true;
  21430. hadMatch = true;
  21431. hadAnyMatch = true;
  21432. storeIFaceMethod = true;
  21433. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  21434. {
  21435. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  21436. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance) && (!mIsComptimeModule))
  21437. {
  21438. // When autocompletion regenerates a single method body but not the whole type then
  21439. // we will see ourselves in the vtable already
  21440. return usedMethod;
  21441. }
  21442. bool isBetter = false;
  21443. bool isWorse = false;
  21444. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  21445. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  21446. if (isBetter == isWorse)
  21447. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  21448. if (isBetter == isWorse)
  21449. {
  21450. if (ambiguityContext != NULL)
  21451. {
  21452. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  21453. }
  21454. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  21455. storeIFaceMethod = true;
  21456. }
  21457. else
  21458. {
  21459. if ((isBetter) && (ambiguityContext != NULL))
  21460. ambiguityContext->Remove(~iTableIdx);
  21461. storeIFaceMethod = isBetter;
  21462. }
  21463. }
  21464. }
  21465. if (storeIFaceMethod)
  21466. {
  21467. if (methodInstance->GetNumGenericParams() != 0)
  21468. _AddVirtualDecl(iMethodInst);
  21469. *iMethodPtr = methodInstance;
  21470. }
  21471. checkMethodDef = checkMethodDef->mNextWithSameName;
  21472. }
  21473. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  21474. {
  21475. if (expectedReturnType != NULL)
  21476. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  21477. else if (hadNameMatch != NULL)
  21478. {
  21479. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  21480. if (error != NULL)
  21481. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  21482. }
  21483. else
  21484. {
  21485. auto propertyDecl = methodDef->GetPropertyDeclaration();
  21486. if (propertyDecl != NULL)
  21487. {
  21488. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  21489. String name;
  21490. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  21491. name = "this[]";
  21492. else if (propertyDecl->mNameNode != NULL)
  21493. propertyDecl->mNameNode->ToString(name);
  21494. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  21495. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  21496. }
  21497. else
  21498. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  21499. }
  21500. }
  21501. }
  21502. // Any overriden virtual methods that were used in interfaces also need to be replaced
  21503. if (methodOverriden != NULL)
  21504. {
  21505. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  21506. {
  21507. if (methodEntry.mMethodRef == methodOverriden)
  21508. methodEntry.mMethodRef = methodInstance;
  21509. }
  21510. }
  21511. return usedMethod;
  21512. }
  21513. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  21514. {
  21515. auto methodDef = methodInstance->mMethodDef;
  21516. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  21517. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  21518. {
  21519. const char* protectionNames[] = { "hidden", "private", "internal", "protected", "protected internal", "public" };
  21520. BF_STATIC_ASSERT(BF_ARRAY_COUNT(protectionNames) == BfProtection_COUNT);
  21521. BfAstNode* protectionRefNode = NULL;
  21522. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  21523. {
  21524. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  21525. if (protectionRefNode == NULL)
  21526. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  21527. if (protectionRefNode == NULL)
  21528. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  21529. }
  21530. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21531. {
  21532. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  21533. if (protectionRefNode == NULL)
  21534. protectionRefNode = methodDeclaration->mNameNode;
  21535. }
  21536. if (protectionRefNode != NULL)
  21537. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  21538. }
  21539. }
  21540. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  21541. {
  21542. auto typeInstance = mCurTypeInstance;
  21543. auto methodDef = methodInstance->mMethodDef;
  21544. if (methodDef->mMethodType == BfMethodType_Ctor)
  21545. return true;
  21546. bool foundOverride = false;
  21547. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  21548. {
  21549. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21550. BfAstNode* refNode = NULL;
  21551. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  21552. refNode = propertyDeclaration->mProtectionSpecifier;
  21553. else if (methodDeclaration != NULL)
  21554. refNode = methodDeclaration->mProtectionSpecifier;
  21555. Fail("Private interface methods must provide a body", refNode);
  21556. }
  21557. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  21558. {
  21559. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  21560. }
  21561. BfAstNode* declaringNode = methodDef->GetRefNode();
  21562. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  21563. {
  21564. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  21565. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  21566. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  21567. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  21568. continue;
  21569. ifaceInst->mTypeDef->PopulateMemberSets();
  21570. BfMethodDef* nextMethod = NULL;
  21571. BfMemberSetEntry* entry = NULL;
  21572. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21573. nextMethod = (BfMethodDef*)entry->mMemberDef;
  21574. while (nextMethod != NULL)
  21575. {
  21576. auto checkMethod = nextMethod;
  21577. nextMethod = nextMethod->mNextWithSameName;
  21578. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21579. if (ifaceMethod == NULL)
  21580. continue;
  21581. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  21582. {
  21583. if (methodDef->mIsOverride)
  21584. {
  21585. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  21586. {
  21587. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  21588. if (error != NULL)
  21589. {
  21590. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  21591. }
  21592. }
  21593. foundOverride = true;
  21594. }
  21595. else if (!methodDef->mIsNew)
  21596. {
  21597. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  21598. }
  21599. }
  21600. }
  21601. }
  21602. if ((methodDef->mIsOverride) && (!foundOverride))
  21603. {
  21604. // This allows us to declare a method in the base definition or in an extension and then provide
  21605. // an implementation in a more-specific extension
  21606. typeInstance->mTypeDef->PopulateMemberSets();
  21607. BfMethodDef* nextMethod = NULL;
  21608. BfMemberSetEntry* entry = NULL;
  21609. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21610. nextMethod = (BfMethodDef*)entry->mMemberDef;
  21611. while (nextMethod != NULL)
  21612. {
  21613. auto checkMethod = nextMethod;
  21614. nextMethod = nextMethod->mNextWithSameName;
  21615. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21616. if (ifaceMethod == NULL)
  21617. continue;
  21618. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  21619. continue;
  21620. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  21621. {
  21622. foundOverride = true;
  21623. }
  21624. }
  21625. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  21626. // {
  21627. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  21628. // if (ifaceMethod == NULL)
  21629. // continue;
  21630. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  21631. // continue;
  21632. //
  21633. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  21634. // {
  21635. // foundOverride = true;
  21636. // }
  21637. // }
  21638. }
  21639. if (methodDef->mIsOverride)
  21640. {
  21641. if (!foundOverride)
  21642. {
  21643. BfTokenNode* overrideToken = NULL;
  21644. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  21645. overrideToken = propertyDeclaration->mVirtualSpecifier;
  21646. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21647. overrideToken = methodDeclaration->mVirtualSpecifier;
  21648. if (overrideToken != NULL)
  21649. {
  21650. Fail("No suitable method found to override", overrideToken, true);
  21651. }
  21652. else
  21653. {
  21654. // Possible cause - DTOR with params
  21655. AssertErrorState();
  21656. }
  21657. }
  21658. return true;
  21659. }
  21660. // Generic methods can't be called virtually
  21661. if (methodInstance->GetNumGenericParams() != 0)
  21662. return true;
  21663. // Only public methods can be called virtually
  21664. if (methodDef->mProtection != BfProtection_Public)
  21665. return true;
  21666. UniqueSlotVirtualMethod(methodInstance);
  21667. return true;
  21668. }
  21669. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  21670. {
  21671. if (methodInstance->mMethodInfoEx == NULL)
  21672. return;
  21673. int wantMinDepth = -1;
  21674. if (mCurTypeInstance != NULL)
  21675. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  21676. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  21677. {
  21678. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  21679. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  21680. wantMinDepth = wantTypeMinDepth;
  21681. }
  21682. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  21683. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  21684. }
  21685. void BfModule::DbgFinish()
  21686. {
  21687. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  21688. return;
  21689. if (mAwaitingInitFinish)
  21690. FinishInit();
  21691. if (mHasForceLinkMarker)
  21692. return;
  21693. String markerName;
  21694. BfIRValue linkMarker;
  21695. if (mBfIRBuilder->DbgHasInfo())
  21696. {
  21697. bool needForceLinking = false;
  21698. for (auto& ownedType : mOwnedTypeInstances)
  21699. {
  21700. bool hasConfirmedReference = false;
  21701. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  21702. {
  21703. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  21704. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  21705. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)) &&
  21706. (methodInstGroup.mHasEmittedReference))
  21707. {
  21708. hasConfirmedReference = true;
  21709. }
  21710. }
  21711. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  21712. needForceLinking = true;
  21713. }
  21714. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  21715. {
  21716. BfMethodState methodState;
  21717. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  21718. methodState.mTempKind = BfMethodState::TempKind_Static;
  21719. mHasForceLinkMarker = true;
  21720. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  21721. SizedArray<BfIRType, 0> paramTypes;
  21722. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  21723. String linkName = "FORCELINKMOD_" + mModuleName;
  21724. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  21725. mBfIRBuilder->SetActiveFunction(func);
  21726. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  21727. mBfIRBuilder->SetInsertPoint(entryBlock);
  21728. auto firstType = mOwnedTypeInstances[0];
  21729. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  21730. SizedArray<BfIRMDNode, 1> diParamTypes;
  21731. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  21732. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  21733. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  21734. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  21735. methodState.mCurScope->mDIScope = diScope;
  21736. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  21737. SizedArray<BfIRValue, 8> args;
  21738. BfExprEvaluator exprEvaluator(this);
  21739. for (auto& ownedType : mOwnedTypeInstances)
  21740. {
  21741. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  21742. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  21743. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  21744. }
  21745. mBfIRBuilder->CreateRetVoid();
  21746. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  21747. }
  21748. }
  21749. }
  21750. bool BfModule::Finish()
  21751. {
  21752. BP_ZONE("BfModule::Finish");
  21753. BfLogSysM("BfModule finish: %p\n", this);
  21754. if (mHadBuildError)
  21755. {
  21756. // Don't AssertErrorState here, this current pass may not have failed but
  21757. // the module was still queued in mFinishedModuleWorkList
  21758. ClearModule();
  21759. return true;
  21760. }
  21761. if (mUsedSlotCount != -1)
  21762. {
  21763. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  21764. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  21765. }
  21766. if ((!mGeneratesCode) && (!mAddedToCount))
  21767. return true;
  21768. BF_ASSERT(mAddedToCount);
  21769. mAddedToCount = false;
  21770. mAwaitingFinish = false;
  21771. mCompiler->mStats.mModulesFinished++;
  21772. if (HasCompiledOutput())
  21773. {
  21774. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  21775. DbgFinish();
  21776. if (mAwaitingInitFinish)
  21777. FinishInit();
  21778. for (auto ownedTypeInst : mOwnedTypeInstances)
  21779. {
  21780. // Generate dbg info and add global variables if we haven't already
  21781. mBfIRBuilder->PopulateType(ownedTypeInst);
  21782. }
  21783. if (mBfIRBuilder->DbgHasInfo())
  21784. {
  21785. mBfIRBuilder->DbgFinalize();
  21786. }
  21787. String objOutputPath;
  21788. String irOutputPath;
  21789. mIsModuleMutable = false;
  21790. //mOutFileNames.Clear();
  21791. BF_ASSERT(((int)mOutFileNames.size() >= mExtensionCount) || (mParentModule != NULL));
  21792. bool writeModule = mBfIRBuilder->HasExports();
  21793. String outputPath;
  21794. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  21795. auto& compilerOpts = mCompiler->mOptions;
  21796. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  21797. auto moduleOptions = GetModuleOptions();
  21798. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  21799. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  21800. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  21801. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  21802. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  21803. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  21804. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  21805. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  21806. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  21807. bool allowWriteToLib = true;
  21808. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  21809. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  21810. {
  21811. codeGenOptions.mWriteToLib = true;
  21812. mWroteToLib = true;
  21813. }
  21814. else
  21815. {
  21816. mWroteToLib = false;
  21817. }
  21818. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  21819. {
  21820. outputPath = mModuleName;
  21821. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  21822. BfModuleFileName moduleFileName;
  21823. if (mParentModule != NULL)
  21824. {
  21825. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  21826. {
  21827. if (checkPair.mValue == this)
  21828. moduleFileName.mProjects = checkPair.mKey;
  21829. }
  21830. }
  21831. moduleFileName.mProjects.Add(mProject);
  21832. if (fileIdx > 0)
  21833. outputPath += StrFormat("@%d", fileIdx + 1);
  21834. if (mCompiler->mOptions.mWriteIR)
  21835. irOutputPath = outputPath + ".ll";
  21836. if (mCompiler->mOptions.mGenerateObj)
  21837. {
  21838. objOutputPath = outputPath + BF_OBJ_EXT;
  21839. moduleFileName.mFileName = objOutputPath;
  21840. }
  21841. else if (mCompiler->mOptions.mWriteIR)
  21842. {
  21843. moduleFileName.mFileName = irOutputPath;
  21844. }
  21845. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  21846. {
  21847. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  21848. }
  21849. moduleFileName.mModuleWritten = writeModule;
  21850. moduleFileName.mWroteToLib = mWroteToLib;
  21851. if (!mOutFileNames.Contains(moduleFileName))
  21852. mOutFileNames.Add(moduleFileName);
  21853. }
  21854. if (mCompiler->IsHotCompile())
  21855. {
  21856. codeGenOptions.mIsHotCompile = true;
  21857. if (mParentModule != NULL)
  21858. mParentModule->mHadHotObjectWrites = true;
  21859. mHadHotObjectWrites = true;
  21860. }
  21861. //TODO: Testing VDATA
  21862. /*if (mModuleName == "vdata")
  21863. {
  21864. codeGenOptions.mOptLevel = 4;
  21865. }*/
  21866. codeGenOptions.GenerateHash();
  21867. BP_ZONE("BfModule::Finish.WriteObjectFile");
  21868. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  21869. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  21870. mLastModuleWrittenRevision = mCompiler->mRevision;
  21871. }
  21872. else
  21873. {
  21874. for (auto type : mOwnedTypeInstances)
  21875. {
  21876. BF_ASSERT((!type->IsIncomplete()) || (type->IsSpecializedByAutoCompleteMethod()));
  21877. }
  21878. }
  21879. for (auto& specModulePair : mSpecializedMethodModules)
  21880. {
  21881. auto specModule = specModulePair.mValue;
  21882. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  21883. {
  21884. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  21885. }
  21886. }
  21887. CleanupFileInstances();
  21888. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  21889. return true;
  21890. }
  21891. void BfModule::ReportMemory(MemReporter* memReporter)
  21892. {
  21893. memReporter->Add(sizeof(BfModule));
  21894. if (mBfIRBuilder != NULL)
  21895. {
  21896. memReporter->BeginSection("IRBuilder_ConstData");
  21897. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  21898. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  21899. memReporter->EndSection();
  21900. memReporter->BeginSection("IRBuilder_BFIR");
  21901. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  21902. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  21903. memReporter->EndSection();
  21904. memReporter->Add(sizeof(BfIRBuilder));
  21905. }
  21906. memReporter->BeginSection("FileInstanceMap");
  21907. memReporter->AddMap(mFileInstanceMap);
  21908. memReporter->AddMap(mNamedFileInstanceMap);
  21909. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  21910. memReporter->EndSection();
  21911. memReporter->AddVec(mOwnedTypeInstances, false);
  21912. memReporter->AddVec(mSpecializedMethodModules, false);
  21913. memReporter->AddVec(mOutFileNames, false);
  21914. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  21915. memReporter->AddMap(mInterfaceSlotRefs, false);
  21916. memReporter->AddMap(mStaticFieldRefs, false);
  21917. memReporter->AddMap(mClassVDataRefs, false);
  21918. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  21919. memReporter->AddMap(mTypeDataRefs, false);
  21920. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  21921. memReporter->AddMap(mDeferredMethodCallData, false);
  21922. memReporter->AddHashSet(mDeferredMethodIds, false);
  21923. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  21924. }
  21925. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  21926. // be transient through the next compile
  21927. void BfModule::ClearModuleData(bool clearTransientData)
  21928. {
  21929. BfLogSysM("ClearModuleData %p\n", this);
  21930. if (mAddedToCount)
  21931. {
  21932. mCompiler->mStats.mModulesFinished++;
  21933. mAddedToCount = false;
  21934. }
  21935. mDICompileUnit = BfIRMDNode();
  21936. if (clearTransientData)
  21937. mIncompleteMethodCount = 0;
  21938. mHasGenericMethods = false;
  21939. // We don't want to clear these because we want it to persist through module extensions-
  21940. // otherwise we may think an extension succeeds even though the base module failed
  21941. //mHadBuildError = false;
  21942. //mHadBuildWarning = false;
  21943. mClassVDataRefs.Clear();
  21944. mClassVDataExtRefs.Clear();
  21945. for (auto& kv : mTypeDataRefs)
  21946. kv.mValue = BfIRValue();
  21947. mStringCharPtrPool.Clear();
  21948. mStringObjectPool.Clear();
  21949. mStaticFieldRefs.Clear();
  21950. BF_ASSERT(!mIgnoreErrors);
  21951. for (auto prevIRBuilder : mPrevIRBuilders)
  21952. delete prevIRBuilder;
  21953. mPrevIRBuilders.Clear();
  21954. for (auto& specPair : mSpecializedMethodModules)
  21955. {
  21956. auto specModule = specPair.mValue;
  21957. specModule->ClearModuleData();
  21958. }
  21959. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  21960. mBuiltInFuncs[i] = BfIRFunction();
  21961. if (mNextAltModule != NULL)
  21962. mNextAltModule->ClearModuleData();
  21963. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  21964. mIsModuleMutable = false;
  21965. delete mBfIRBuilder;
  21966. mBfIRBuilder = NULL;
  21967. mWantsIRIgnoreWrites = false;
  21968. }
  21969. void BfModule::DisownMethods()
  21970. {
  21971. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  21972. mBuiltInFuncs[i] = BfIRFunction();
  21973. BfModule* methodModule = this;
  21974. if (mParentModule != NULL)
  21975. methodModule = mParentModule;
  21976. for (auto typeInst : methodModule->mOwnedTypeInstances)
  21977. {
  21978. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  21979. {
  21980. if (methodGroup.mDefault != NULL)
  21981. {
  21982. if (methodGroup.mDefault->mIRFunction)
  21983. {
  21984. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  21985. if (methodGroup.mDefault->mDeclModule == this)
  21986. {
  21987. methodGroup.mDefault->mIRFunction = BfIRFunction();
  21988. }
  21989. }
  21990. }
  21991. if (methodGroup.mMethodSpecializationMap != NULL)
  21992. {
  21993. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  21994. {
  21995. auto methodInstance = mapPair.mValue;
  21996. if (methodInstance->mDeclModule == this)
  21997. {
  21998. methodInstance->mIRFunction = BfIRFunction();
  21999. }
  22000. }
  22001. }
  22002. }
  22003. }
  22004. }
  22005. void BfModule::ClearModule()
  22006. {
  22007. ClearModuleData();
  22008. DisownMethods();
  22009. for (auto& specPair : mSpecializedMethodModules)
  22010. {
  22011. auto specModule = specPair.mValue;
  22012. specModule->ClearModule();
  22013. }
  22014. if (mNextAltModule != NULL)
  22015. mNextAltModule->ClearModule();
  22016. }