BfModule.cpp 938 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574
  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 (disable:4267)
  29. //#include "llvm/Support/Compiler.h"
  30. //#include "llvm/IR/IRBuilder.h"
  31. //#include "llvm/IR/Type.h"
  32. #include "llvm/IR/DIBuilder.h"
  33. //#include "llvm/IR/DebugInfo.h"
  34. //#include "llvm/IR/Argument.h"
  35. //#include "llvm/IR/Constants.h"
  36. #pragma warning(pop)
  37. //////////////////////////////////////////////////////////////////////////
  38. static bool gDebugStuff = false;
  39. USING_NS_BF;
  40. //////////////////////////////////////////////////////////////////////////
  41. void BfLocalVariable::Init()
  42. {
  43. if (mResolvedType->IsValuelessType())
  44. {
  45. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  46. return;
  47. }
  48. if (mAssignedKind != BfLocalVarAssignKind_None)
  49. return;
  50. bool isStruct = mResolvedType->IsStruct();
  51. if (mResolvedType->IsRef())
  52. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  53. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  54. {
  55. auto resolvedTypeRef = mResolvedType;
  56. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  57. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  58. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  59. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  60. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  61. {
  62. // Base ctor is responsible for initializing its own fields
  63. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  64. }
  65. if (mUnassignedFieldFlags == 0)
  66. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  67. }
  68. else
  69. {
  70. mUnassignedFieldFlags = 1;
  71. }
  72. }
  73. BfLocalMethod::~BfLocalMethod()
  74. {
  75. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  76. if (mMethodDeclaration != NULL)
  77. {
  78. mSource->mRefCount--;
  79. BF_ASSERT(mSource->mRefCount >= 0);
  80. }
  81. delete mMethodInstanceGroup;
  82. delete mMethodDef;
  83. }
  84. void BfLocalMethod::Dispose()
  85. {
  86. if (mMethodInstanceGroup == NULL)
  87. return;
  88. if (mMethodInstanceGroup->mDefault != NULL)
  89. mMethodInstanceGroup->mDefault->Dispose();
  90. if (mMethodInstanceGroup->mMethodSpecializationMap != NULL)
  91. {
  92. for (auto& kv : *mMethodInstanceGroup->mMethodSpecializationMap)
  93. kv.mValue->Dispose();
  94. }
  95. }
  96. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  97. {
  98. mIsChained = doChain;
  99. if (outerLocalAssignData == NULL)
  100. return;
  101. mChainedAssignData = outerLocalAssignData;
  102. if (!doChain)
  103. {
  104. outerLocalAssignData->BreakExtendChain();
  105. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  106. }
  107. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  108. }
  109. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  110. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  111. // if ((GetValue(out a)) && (GetValue(out b)) {}
  112. void BfDeferredLocalAssignData::BreakExtendChain()
  113. {
  114. if (!mIsChained)
  115. return;
  116. mIsChained = false;
  117. if (mChainedAssignData == NULL)
  118. return;
  119. mChainedAssignData->BreakExtendChain();
  120. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  121. }
  122. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  123. {
  124. BreakExtendChain();
  125. if (otherLocalAssignData.mLeftBlockUncond)
  126. {
  127. // Intersection of self and infinity is self
  128. }
  129. else if (mLeftBlockUncond)
  130. {
  131. // Intersection of infinity and other is other
  132. mAssignedLocals = otherLocalAssignData.mAssignedLocals;
  133. }
  134. else
  135. {
  136. for (int i = 0; i < (int)mAssignedLocals.size(); )
  137. {
  138. auto& local = mAssignedLocals[i];
  139. bool wantRemove = true;
  140. bool foundOtherFields = false;
  141. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  142. {
  143. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  144. {
  145. if ((otherLocalAssignData.mLocalVarField == local.mLocalVarField) || (otherLocalAssignData.mLocalVarField == -1))
  146. {
  147. if (otherLocalAssignData.mAssignKind == BfLocalVarAssignKind_Conditional)
  148. local.mAssignKind = BfLocalVarAssignKind_Conditional;
  149. wantRemove = false;
  150. }
  151. else
  152. foundOtherFields = true;
  153. }
  154. }
  155. if ((wantRemove) && (foundOtherFields))
  156. {
  157. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  158. {
  159. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  160. {
  161. mAssignedLocals.Add(otherLocalAssignData);
  162. }
  163. }
  164. }
  165. if (wantRemove)
  166. {
  167. mAssignedLocals.RemoveAt(i);
  168. }
  169. else
  170. i++;
  171. }
  172. }
  173. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  174. mLeftBlockUncond = mLeftBlockUncond && otherLocalAssignData.mLeftBlockUncond;
  175. }
  176. void BfDeferredLocalAssignData::Validate() const
  177. {
  178. for (auto var : mAssignedLocals)
  179. {
  180. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  181. }
  182. }
  183. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  184. {
  185. BreakExtendChain();
  186. Validate();
  187. otherLocalAssignData.Validate();
  188. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  189. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  190. {
  191. if (!mAssignedLocals.Contains(*otherItr))
  192. mAssignedLocals.push_back(*otherItr);
  193. ++otherItr;
  194. }
  195. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  196. mLeftBlockUncond = mLeftBlockUncond || otherLocalAssignData.mLeftBlockUncond;
  197. }
  198. BfMethodState::~BfMethodState()
  199. {
  200. BF_ASSERT(mPendingNullConditional == NULL);
  201. if (mPrevMethodState != NULL)
  202. {
  203. BF_ASSERT(mCurAccessId == 1);
  204. BF_ASSERT(mCurLocalVarId <= 0);
  205. }
  206. for (auto local : mLocals)
  207. {
  208. if (local->mIsBumpAlloc)
  209. local->~BfLocalVariable();
  210. else
  211. delete local;
  212. }
  213. for (auto& kv : mLambdaCache)
  214. delete kv.mValue;
  215. }
  216. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  217. {
  218. auto checkMethodState = this;
  219. while (checkMethodState != NULL)
  220. {
  221. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  222. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  223. return checkMethodState;
  224. checkMethodState = checkMethodState->mPrevMethodState;
  225. }
  226. BF_FATAL("Failed to find method state for localvar");
  227. return NULL;
  228. }
  229. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx, BfLocalVarAssignKind assignKind, bool isFromDeferredAssignData)
  230. {
  231. auto localVarMethodState = GetMethodStateForLocal(localVar);
  232. if (localVarMethodState != this)
  233. {
  234. return;
  235. }
  236. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  237. {
  238. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  239. // 'a' is always defined, but 'b' isn't:
  240. // if (Check(out a) || Check(out b)) { } int z = a;
  241. auto deferredLocalAssignData = mDeferredLocalAssignData;
  242. if ((deferredLocalAssignData != NULL) &&
  243. (deferredLocalAssignData->mIsIfCondition) &&
  244. (!deferredLocalAssignData->mIfMayBeSkipped))
  245. {
  246. ifDeferredLocalAssignData = deferredLocalAssignData;
  247. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  248. }
  249. while ((deferredLocalAssignData != NULL) &&
  250. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  251. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  252. if (assignKind == BfLocalVarAssignKind_None)
  253. assignKind = ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mLeftBlock)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  254. if (localVar->mAssignedKind >= assignKind)
  255. {
  256. // Leave it alone
  257. }
  258. else if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  259. {
  260. if (fieldIdx >= 0)
  261. {
  262. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  263. if (localVar->mResolvedType->IsUnion())
  264. {
  265. // We need more 'smarts' to determine assignment of unions
  266. localVar->mUnassignedFieldFlags = 0;
  267. }
  268. if (localVar->mUnassignedFieldFlags == 0)
  269. {
  270. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  271. localVar->mAssignedKind = assignKind;
  272. }
  273. }
  274. else
  275. {
  276. localVar->mAssignedKind = assignKind;
  277. }
  278. }
  279. else
  280. {
  281. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  282. BfAssignedLocal defineVal = {localVar, fieldIdx, assignKind};
  283. if (!deferredLocalAssignData->Contains(defineVal))
  284. deferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  285. if (ifDeferredLocalAssignData != NULL)
  286. {
  287. if (!ifDeferredLocalAssignData->Contains(defineVal))
  288. ifDeferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  289. }
  290. }
  291. }
  292. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  293. }
  294. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  295. {
  296. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  297. if (deferredLocalAssignData.mLeftBlockUncond)
  298. {
  299. for (int localIdx = 0; localIdx < (int)mLocals.size(); localIdx++)
  300. {
  301. auto localDef = mLocals[localIdx];
  302. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  303. {
  304. bool hadAssignment = false;
  305. if (mDeferredLocalAssignData != NULL)
  306. {
  307. for (auto& entry : mDeferredLocalAssignData->mAssignedLocals)
  308. if (entry.mLocalVar == localDef)
  309. hadAssignment = true;
  310. }
  311. if (!hadAssignment)
  312. {
  313. LocalDefined(localDef);
  314. }
  315. }
  316. }
  317. }
  318. else
  319. {
  320. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  321. {
  322. LocalDefined(assignedLocal.mLocalVar, assignedLocal.mLocalVarField, assignedLocal.mAssignKind, true);
  323. }
  324. }
  325. }
  326. void BfMethodState::Reset()
  327. {
  328. mHeadScope.mDeferredCallEntries.DeleteAll();
  329. }
  330. //////////////////////////////////////////////////////////////////////////
  331. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  332. {
  333. Entry* entry = NULL;
  334. if (mEntries.TryAdd(id, NULL, &entry))
  335. {
  336. entry->mInterfaceEntry = interfaceEntry;
  337. entry->mMethodIdx = methodIdx;
  338. }
  339. if (!entry->mCandidates.Contains(candidateA))
  340. entry->mCandidates.push_back(candidateA);
  341. if (!entry->mCandidates.Contains(candidateB))
  342. entry->mCandidates.push_back(candidateB);
  343. }
  344. void BfAmbiguityContext::Remove(int id)
  345. {
  346. mEntries.Remove(id);
  347. }
  348. void BfAmbiguityContext::Finish()
  349. {
  350. for (auto& entryPair : mEntries)
  351. {
  352. int id = entryPair.mKey;
  353. auto entry = &entryPair.mValue;
  354. if (id >= 0)
  355. {
  356. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  357. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  358. if (error != NULL)
  359. {
  360. for (auto candidate : entry->mCandidates)
  361. {
  362. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  363. mModule->MethodToString(candidate, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType)).c_str()), candidate->mMethodDef->GetRefNode());
  364. }
  365. }
  366. }
  367. else
  368. {
  369. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  370. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  371. if (error != NULL)
  372. {
  373. for (auto candidate : entry->mCandidates)
  374. {
  375. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  376. mModule->MethodToString(candidate, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType)).c_str()), candidate->mMethodDef->GetRefNode());
  377. }
  378. }
  379. }
  380. }
  381. mEntries.Clear();
  382. }
  383. //////////////////////////////////////////////////////////////////////////
  384. class HasAppendAllocVisitor : BfElementVisitor
  385. {
  386. public:
  387. bool mHas;
  388. public:
  389. HasAppendAllocVisitor()
  390. {
  391. mHas = false;
  392. }
  393. void Visit(BfObjectCreateExpression* objCreateExpr)
  394. {
  395. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  396. {
  397. if (newToken->GetToken() == BfToken_Append)
  398. {
  399. mHas = true;
  400. }
  401. }
  402. }
  403. bool HasAppendAlloc(BfAstNode* node)
  404. {
  405. mHas = false;
  406. VisitChild(node);
  407. return mHas;
  408. }
  409. };
  410. class AppendAllocVisitor : public BfStructuralVisitor
  411. {
  412. public:
  413. BfModule* mModule;
  414. HasAppendAllocVisitor mHasAppendAllocVisitor;
  415. BfTypedValue mConstAccum;
  416. bool mFailed;
  417. bool mIsFirstConstPass;
  418. bool mHasAppendWantMark;
  419. int mCurAppendAlign;
  420. public:
  421. AppendAllocVisitor()
  422. {
  423. mFailed = false;
  424. mIsFirstConstPass = false;
  425. mHasAppendWantMark = false;
  426. mCurAppendAlign = 1;
  427. }
  428. void EmitAppendAlign(int align, int sizeMultiple = 0)
  429. {
  430. if (align <= 1)
  431. return;
  432. if (mIsFirstConstPass)
  433. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  434. if (sizeMultiple == 0)
  435. sizeMultiple = align;
  436. if (mCurAppendAlign == 0)
  437. mCurAppendAlign = sizeMultiple;
  438. else
  439. {
  440. if (sizeMultiple % align == 0)
  441. mCurAppendAlign = align;
  442. else
  443. mCurAppendAlign = sizeMultiple % align;
  444. }
  445. BF_ASSERT(mCurAppendAlign > 0);
  446. if (mConstAccum)
  447. {
  448. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  449. if (constant != NULL)
  450. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  451. else
  452. BF_ASSERT(mIsFirstConstPass);
  453. return;
  454. }
  455. mModule->EmitAppendAlign(align, sizeMultiple);
  456. }
  457. void Visit(BfAstNode* astNode) override
  458. {
  459. mModule->VisitChild(astNode);
  460. }
  461. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  462. {
  463. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  464. {
  465. if (newToken->GetToken() == BfToken_Append)
  466. {
  467. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  468. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  469. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  470. BfArrayType* arrayType = NULL;
  471. bool isArrayAlloc = false;
  472. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  473. SizedArray<BfIRValue, 2> dimLengthVals;
  474. BfType* origResolvedTypeRef = NULL;
  475. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  476. {
  477. if (variableDecl != NULL)
  478. {
  479. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  480. if (origResolvedTypeRef->IsObject())
  481. {
  482. if (origResolvedTypeRef->IsArray())
  483. {
  484. arrayType = (BfArrayType*)origResolvedTypeRef;
  485. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  486. isArrayAlloc = true;
  487. }
  488. }
  489. else if (origResolvedTypeRef->IsPointer())
  490. {
  491. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  492. }
  493. }
  494. }
  495. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  496. {
  497. isArrayAlloc = true;
  498. bool handled = false;
  499. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  500. {
  501. if (variableDecl->mTypeRef != NULL)
  502. {
  503. auto variableType = mModule->ResolveTypeRef(variableDecl->mTypeRef);
  504. if (variableType != NULL)
  505. {
  506. if (variableType->IsArray())
  507. origResolvedTypeRef = variableType->GetUnderlyingType();
  508. }
  509. handled = true;
  510. }
  511. }
  512. if (!handled)
  513. {
  514. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType, BfPopulateType_Declaration);
  515. }
  516. if (origResolvedTypeRef == NULL)
  517. {
  518. mModule->AssertErrorState();
  519. return;
  520. }
  521. int dimensions = 1;
  522. if (arrayTypeRef->mParams.size() != 0)
  523. {
  524. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  525. for (auto arg : arrayTypeRef->mParams)
  526. {
  527. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  528. {
  529. if (tokenNode->GetToken() == BfToken_Comma)
  530. {
  531. if (isRawArrayAlloc)
  532. {
  533. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  534. continue;
  535. }
  536. dimensions++;
  537. continue;
  538. }
  539. }
  540. auto expr = BfNodeDynCast<BfExpression>(arg);
  541. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  542. {
  543. mModule->CreateValueFromExpression(expr, intType);
  544. continue;
  545. }
  546. BfTypedValue dimLength;
  547. if (expr == NULL)
  548. {
  549. // Not specified
  550. dimLengthVals.push_back(BfIRValue());
  551. continue;
  552. }
  553. if (arg != NULL)
  554. dimLength = mModule->CreateValueFromExpression(expr, intType);
  555. if (!dimLength)
  556. {
  557. dimLength = mModule->GetDefaultTypedValue(intType);
  558. }
  559. dimLengthVals.push_back(dimLength.mValue);
  560. }
  561. }
  562. if (!isRawArrayAlloc)
  563. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  564. }
  565. if (origResolvedTypeRef == NULL)
  566. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  567. if (origResolvedTypeRef == NULL)
  568. {
  569. mModule->AssertErrorState();
  570. return;
  571. }
  572. if (origResolvedTypeRef->WantsGCMarking())
  573. mHasAppendWantMark = true;
  574. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  575. auto resolvedTypeRef = origResolvedTypeRef;
  576. auto resultType = resolvedTypeRef;
  577. BfIRValue sizeValue;
  578. int curAlign = 0;
  579. if (isArrayAlloc)
  580. {
  581. int dimensions = 1;
  582. if (arrayType != NULL)
  583. dimensions = arrayType->mDimensions;
  584. bool sizeFailed = false;
  585. //
  586. {
  587. BfAstNode* initNode = objCreateExpr;
  588. for (int dim = 0; dim < dimensions; dim++)
  589. {
  590. BfAstNode* nextInitNode = NULL;
  591. int dimSize = -1;
  592. if (initNode == objCreateExpr)
  593. {
  594. dimSize = objCreateExpr->mArguments.size();
  595. if (!objCreateExpr->mArguments.IsEmpty())
  596. nextInitNode = objCreateExpr->mArguments[0];
  597. }
  598. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  599. {
  600. dimSize = (int)tupleNode->mCommas.size() + 1;
  601. }
  602. if (dimSize >= 0)
  603. {
  604. if (dim >= dimLengthVals.size())
  605. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  606. }
  607. else
  608. {
  609. sizeFailed = true;
  610. }
  611. }
  612. }
  613. BfIRValue allocCount;
  614. if (!sizeFailed)
  615. {
  616. if (!dimLengthVals.IsEmpty())
  617. {
  618. allocCount = dimLengthVals[0];
  619. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  620. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  621. }
  622. }
  623. if (!allocCount)
  624. {
  625. mFailed = true;
  626. if (!mIsFirstConstPass)
  627. {
  628. if (!mConstAccum)
  629. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  630. return;
  631. }
  632. }
  633. mModule->PopulateType(resultType, resultType->IsValueType() ? BfPopulateType_Data : BfPopulateType_Declaration);
  634. if (isRawArrayAlloc)
  635. {
  636. curAlign = resultType->mAlign;
  637. EmitAppendAlign(resultType->mAlign);
  638. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  639. }
  640. else
  641. {
  642. if (arrayType == NULL)
  643. arrayType = mModule->CreateArrayType(resultType, 1);
  644. // Array is a special case where the total size isn't aligned with mAlign
  645. // since we add arbitrary elements to the end without padding the end to align
  646. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  647. curAlign = arrayType->mAlign;
  648. auto firstElementField = &arrayType->mFieldInstances.back();
  649. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  650. sizeValue = mModule->GetConstValue(arrayClassSize);
  651. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  652. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  653. }
  654. }
  655. else
  656. {
  657. auto typeInst = resultType->ToTypeInstance();
  658. if (typeInst != NULL)
  659. {
  660. curAlign = typeInst->mInstAlign;
  661. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  662. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  663. }
  664. else
  665. {
  666. curAlign = resultType->mAlign;
  667. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  668. sizeValue = mModule->GetConstValue(resultType->mSize);
  669. }
  670. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  671. BfExprEvaluator exprEvaluator(mModule);
  672. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  673. BfFunctionBindResult bindResult;
  674. bindResult.mWantsArgs = true;
  675. exprEvaluator.mFunctionBindResult = &bindResult;
  676. SizedArray<BfExpression*, 8> copiedArgs;
  677. for (BfExpression* arg : objCreateExpr->mArguments)
  678. copiedArgs.push_back(arg);
  679. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  680. BfResolvedArgs argValues(&sizedArgExprs);
  681. if (typeInst != NULL)
  682. {
  683. exprEvaluator.ResolveArgValues(argValues);
  684. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, BfMethodGenericArguments(), BfAllowAppendKind_Infer);
  685. }
  686. exprEvaluator.mFunctionBindResult = NULL;
  687. if (bindResult.mMethodInstance != NULL)
  688. {
  689. if (bindResult.mMethodInstance->mMethodDef->HasAppend())
  690. {
  691. auto calcAppendArgs = bindResult.mIRArgs;
  692. BF_ASSERT(calcAppendArgs[0].IsFake());
  693. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  694. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  695. auto subDependSize = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, calcAppendArgs);
  696. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  697. {
  698. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  699. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  700. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  701. }
  702. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  703. if ((!subDependSize) && (!mConstAccum))
  704. {
  705. BF_ASSERT(calcAppendMethodModule.mFunc);
  706. subDependSize = exprEvaluator.CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  707. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  708. }
  709. if (subDependSize)
  710. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  711. else
  712. mFailed = true;
  713. }
  714. }
  715. }
  716. if (sizeValue)
  717. {
  718. if (mConstAccum)
  719. {
  720. if (!sizeValue.IsConst())
  721. {
  722. mFailed = true;
  723. if (!mIsFirstConstPass)
  724. return;
  725. }
  726. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  727. }
  728. else
  729. {
  730. auto prevVal = mModule->mBfIRBuilder->CreateAlignedLoad(accumValuePtr, intPtrType->mAlign);
  731. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  732. mModule->mBfIRBuilder->CreateAlignedStore(addedVal, accumValuePtr, intPtrType->mAlign);
  733. }
  734. }
  735. }
  736. }
  737. }
  738. void Visit(BfObjectCreateExpression* objCreateExpr) override
  739. {
  740. DoObjectCreate(objCreateExpr, NULL);
  741. }
  742. void Visit(BfVariableDeclaration* varDecl) override
  743. {
  744. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  745. {
  746. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  747. DoObjectCreate(objectCreateExpr, varDecl);
  748. else
  749. VisitChild(varDecl->mInitializer);
  750. if (varDecl->mNameNode != NULL)
  751. {
  752. BfLocalVariable* localDef = new BfLocalVariable();
  753. localDef->mName = varDecl->mNameNode->ToString();
  754. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  755. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  756. localDef->mIsReadOnly = true;
  757. localDef->mParamFailed = true;
  758. localDef->mReadFromId = 0;
  759. mModule->AddLocalVariableDef(localDef);
  760. }
  761. }
  762. else
  763. {
  764. mModule->Visit(varDecl);
  765. }
  766. }
  767. void Visit(BfExpressionStatement* exprStatement) override
  768. {
  769. VisitChild(exprStatement->mExpression);
  770. }
  771. // void Visit(BfIfStatement* ifStmt) override
  772. // {
  773. // mModule->DoIfStatement(ifStmt,
  774. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  775. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  776. // }
  777. void Visit(BfBlock* block) override
  778. {
  779. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  780. return;
  781. int appendAllocIdx = -1;
  782. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  783. {
  784. auto child = block->mChildArr.mVals[childIdx];
  785. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  786. {
  787. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  788. {
  789. auto emitChild = block->mChildArr.mVals[emitIdx];
  790. mModule->UpdateSrcPos(emitChild);
  791. VisitChild(emitChild);
  792. if ((mFailed) && (!mIsFirstConstPass))
  793. break;
  794. }
  795. break;
  796. }
  797. }
  798. }
  799. };
  800. //////////////////////////////////////////////////////////////////////////
  801. BfModule* gLastCreatedModule = NULL;
  802. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  803. {
  804. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  805. gLastCreatedModule = this;
  806. mContext = context;
  807. mModuleName = moduleName;
  808. if (!moduleName.empty())
  809. {
  810. StringT<256> upperModuleName = moduleName;
  811. MakeUpper(upperModuleName);
  812. mContext->mUsedModuleNames.Add(upperModuleName);
  813. }
  814. mAddedToCount = false;
  815. mParentModule = NULL;
  816. mNextAltModule = NULL;
  817. mBfIRBuilder = NULL;
  818. mWantsIRIgnoreWrites = false;
  819. mModuleOptions = NULL;
  820. mLastUsedRevision = -1;
  821. mUsedSlotCount = -1;
  822. mIsReified = true;
  823. mGeneratesCode = true;
  824. mReifyQueued = false;
  825. mIsSpecialModule = false;
  826. mIsComptimeModule = false;
  827. mIsScratchModule = false;
  828. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  829. mHadBuildError = false;
  830. mHadBuildWarning = false;
  831. mIgnoreErrors = false;
  832. mHadIgnoredError = false;
  833. mIgnoreWarnings = false;
  834. mReportErrors = true;
  835. mIsInsideAutoComplete = false;
  836. mIsDeleting = false;
  837. mSkipInnerLookup = false;
  838. mIsHotModule = false;
  839. mSetIllegalSrcPosition = false;
  840. mNoResolveGenericParams = false;
  841. mWroteToLib = false;
  842. mContext = context;
  843. mCompiler = context->mCompiler;
  844. mSystem = mCompiler->mSystem;
  845. mProject = NULL;
  846. mCurMethodState = NULL;
  847. mAttributeState = NULL;
  848. mCurLocalMethodId = 0;
  849. mParentNodeEntry = NULL;
  850. mRevision = -1;
  851. mRebuildIdx = 0;
  852. mLastModuleWrittenRevision = 0;
  853. mIsModuleMutable = false;
  854. mExtensionCount = 0;
  855. mIncompleteMethodCount = 0;
  856. mOnDemandMethodCount = 0;
  857. mHasGenericMethods = false;
  858. mCurMethodInstance = NULL;
  859. mCurTypeInstance = NULL;
  860. mAwaitingInitFinish = false;
  861. mAwaitingFinish = false;
  862. mHasFullDebugInfo = false;
  863. mHadHotObjectWrites = false;
  864. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  865. mBuiltInFuncs[i] = BfIRFunction();
  866. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  867. }
  868. void BfReportMemory();
  869. BfModule::~BfModule()
  870. {
  871. mRevision = -2;
  872. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  873. if (!mIsDeleting)
  874. RemoveModuleData();
  875. }
  876. void BfModule::RemoveModuleData()
  877. {
  878. BF_ASSERT(!mIsDeleting);
  879. if (!mModuleName.empty())
  880. {
  881. // Note: module names not necessarily unique
  882. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  883. }
  884. CleanupFileInstances();
  885. delete mBfIRBuilder;
  886. mBfIRBuilder = NULL;
  887. //delete mCpu;
  888. for (auto prevModule : mPrevIRBuilders)
  889. delete prevModule;
  890. mPrevIRBuilders.Clear();
  891. for (auto& pairVal : mDeferredMethodCallData)
  892. delete pairVal.mValue;
  893. mDeferredMethodCallData.Clear();
  894. mDeferredMethodIds.Clear();
  895. for (auto& specModulePair : mSpecializedMethodModules)
  896. delete specModulePair.mValue;
  897. mSpecializedMethodModules.Clear();
  898. if (mNextAltModule != NULL)
  899. delete mNextAltModule;
  900. mNextAltModule = NULL;
  901. if (mModuleOptions != NULL)
  902. delete mModuleOptions;
  903. mModuleOptions = NULL;
  904. BfReportMemory();
  905. }
  906. void BfModule::Init(bool isFullRebuild)
  907. {
  908. mContext->mFinishedModuleWorkList.Remove(this);
  909. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  910. BF_ASSERT(mIsReified);
  911. if (!mIsScratchModule)
  912. {
  913. mCompiler->mStats.mModulesStarted++;
  914. if (mIsReified)
  915. mCompiler->mStats.mReifiedModuleCount++;
  916. mAddedToCount = true;
  917. }
  918. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  919. mFuncReferences.Clear();
  920. mClassVDataRefs.Clear();
  921. mClassVDataExtRefs.Clear();
  922. //mTypeDataRefs.Clear();
  923. mDbgRawAllocDataRefs.Clear();
  924. CleanupFileInstances();
  925. mStaticFieldRefs.Clear();
  926. //mInterfaceSlotRefs.Clear();
  927. // If we are just doing an extension then the ownede types aren't rebuilt.
  928. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  929. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  930. if (isFullRebuild)
  931. mRevision = mCompiler->mRevision;
  932. BF_ASSERT(mCurTypeInstance == NULL);
  933. mIsModuleMutable = true;
  934. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  935. if (!mIsComptimeModule)
  936. {
  937. #ifdef _DEBUG
  938. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  939. #else
  940. EnsureIRBuilder(false);
  941. #endif
  942. }
  943. mCurMethodState = NULL;
  944. mAwaitingInitFinish = true;
  945. mOnDemandMethodCount = 0;
  946. mAwaitingFinish = false;
  947. mHasForceLinkMarker = false;
  948. mUsedSlotCount = -1;
  949. }
  950. bool BfModule::WantsFinishModule()
  951. {
  952. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  953. }
  954. bool BfModule::IsHotCompile()
  955. {
  956. return mCompiler->IsHotCompile() && !mIsComptimeModule;
  957. }
  958. void BfModule::FinishInit()
  959. {
  960. BfLogSysM("FinishInit %@ %s\n", this, mModuleName.c_str());
  961. BF_ASSERT(mAwaitingInitFinish);
  962. auto moduleOptions = GetModuleOptions();
  963. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  964. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple, mCompiler->mOptions.mTargetCPU);
  965. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  966. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  967. {
  968. // Og+ requires debug info
  969. moduleOptions.mEmitDebugInfo = 1;
  970. }
  971. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  972. if (mIsComptimeModule)
  973. mHasFullDebugInfo = true;
  974. if (((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified)) ||
  975. (mIsComptimeModule))
  976. {
  977. mBfIRBuilder->DbgInit();
  978. }
  979. else
  980. mHasFullDebugInfo = false;
  981. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  982. ((moduleOptions.mEmitDebugInfo != 0)))
  983. {
  984. if (mCompiler->mOptions.IsCodeView())
  985. {
  986. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  987. }
  988. else
  989. {
  990. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  991. }
  992. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  993. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  994. }
  995. mAwaitingInitFinish = false;
  996. }
  997. void BfModule::CalcGeneratesCode()
  998. {
  999. if ((!mIsReified) || (mIsScratchModule))
  1000. {
  1001. mGeneratesCode = false;
  1002. return;
  1003. }
  1004. mGeneratesCode = false;
  1005. for (auto typeInst : mOwnedTypeInstances)
  1006. if (!typeInst->IsInterface())
  1007. mGeneratesCode = true;
  1008. }
  1009. void BfModule::ReifyModule()
  1010. {
  1011. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  1012. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  1013. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  1014. mIsReified = true;
  1015. CalcGeneratesCode();
  1016. mReifyQueued = false;
  1017. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  1018. mCompiler->mStats.mModulesReified++;
  1019. }
  1020. void BfModule::UnreifyModule()
  1021. {
  1022. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  1023. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  1024. mIsReified = false;
  1025. CalcGeneratesCode();
  1026. mReifyQueued = false;
  1027. StartNewRevision(RebuildKind_None, true);
  1028. mCompiler->mStats.mModulesUnreified++;
  1029. }
  1030. void BfModule::CleanupFileInstances()
  1031. {
  1032. for (auto& itr : mNamedFileInstanceMap)
  1033. {
  1034. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  1035. delete itr.mValue;
  1036. }
  1037. mCurFilePosition.mFileInstance = NULL;//
  1038. mFileInstanceMap.Clear();
  1039. mNamedFileInstanceMap.Clear();
  1040. }
  1041. void BfModule::Cleanup()
  1042. {
  1043. CleanupFileInstances();
  1044. }
  1045. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  1046. {
  1047. if (HasCompiledOutput())
  1048. {
  1049. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  1050. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  1051. {
  1052. StartExtension();
  1053. }
  1054. }
  1055. else
  1056. {
  1057. EnsureIRBuilder();
  1058. }
  1059. }
  1060. void BfModule::SetupIRBuilder(bool dbgVerifyCodeGen)
  1061. {
  1062. if (mIsScratchModule)
  1063. {
  1064. mBfIRBuilder->mIgnoreWrites = true;
  1065. BF_ASSERT(!dbgVerifyCodeGen);
  1066. }
  1067. #ifdef _DEBUG
  1068. if (mCompiler->mIsResolveOnly)
  1069. {
  1070. // For "deep" verification testing
  1071. /*if (!mIsSpecialModule)
  1072. dbgVerifyCodeGen = true;*/
  1073. // We only want to turn this off on smaller builds for testing
  1074. mBfIRBuilder->mIgnoreWrites = true;
  1075. if (dbgVerifyCodeGen)
  1076. mBfIRBuilder->mIgnoreWrites = false;
  1077. if (!mBfIRBuilder->mIgnoreWrites)
  1078. {
  1079. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  1080. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1081. }
  1082. }
  1083. else if (!mGeneratesCode)
  1084. {
  1085. mBfIRBuilder->mIgnoreWrites = true;
  1086. }
  1087. else
  1088. {
  1089. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  1090. // code as we walk the AST
  1091. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1092. if (
  1093. (mModuleName == "-")
  1094. //|| (mModuleName == "")
  1095. //|| (mModuleName == "Tests_FuncRefs")
  1096. )
  1097. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1098. // Just for testing!
  1099. //mBfIRBuilder->mIgnoreWrites = true;
  1100. }
  1101. #else
  1102. if (mCompiler->mIsResolveOnly)
  1103. {
  1104. // Always ignore writes in resolveOnly for release builds
  1105. mBfIRBuilder->mIgnoreWrites = true;
  1106. }
  1107. else
  1108. {
  1109. // Just for memory testing! This breaks everything.
  1110. //mBfIRBuilder->mIgnoreWrites = true;
  1111. // For "deep" verification testing
  1112. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1113. }
  1114. #endif
  1115. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  1116. }
  1117. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  1118. {
  1119. if (mIsDeleting)
  1120. {
  1121. mCompiler->RequestExtraCompile();
  1122. InternalError("EnsureIRBuilder on deleted module");
  1123. }
  1124. if (mBfIRBuilder == NULL)
  1125. {
  1126. if ((!mIsScratchModule) && (!mAddedToCount))
  1127. {
  1128. mCompiler->mStats.mModulesStarted++;
  1129. mAddedToCount = true;
  1130. }
  1131. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  1132. /*if (mCompiler->mIsResolveOnly)
  1133. BF_ASSERT(mIsResolveOnly);*/
  1134. mBfIRBuilder = new BfIRBuilder(this);
  1135. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  1136. SetupIRBuilder(dbgVerifyCodeGen);
  1137. }
  1138. }
  1139. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1140. {
  1141. String name = "FORCELINKMOD_" + module->mModuleName;
  1142. if (outName != NULL)
  1143. *outName = name;
  1144. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1145. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1146. }
  1147. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1148. {
  1149. BP_ZONE("BfModule::StartNewRevision");
  1150. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1151. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1152. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1153. if (mCompiler->mCompileState == BfCompiler::CompileState_Cleanup)
  1154. {
  1155. // Cleaning up local methods may cause some necessary NewRevisions
  1156. force = true;
  1157. }
  1158. // Already on new revision?
  1159. if ((mRevision == mCompiler->mRevision) && (!force))
  1160. return;
  1161. mHadBuildError = false;
  1162. mHadBuildWarning = false;
  1163. mExtensionCount = 0;
  1164. mRevision = mCompiler->mRevision;
  1165. mRebuildIdx++;
  1166. ClearModuleData(!force);
  1167. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1168. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1169. {
  1170. mStringPoolRefs.Clear();
  1171. mUnreifiedStringPoolRefs.Clear();
  1172. }
  1173. mDllImportEntries.Clear();
  1174. mImportFileNames.Clear();
  1175. for (auto& pairVal : mDeferredMethodCallData)
  1176. delete pairVal.mValue;
  1177. mDeferredMethodCallData.Clear();
  1178. mDeferredMethodIds.Clear();
  1179. mModuleRefs.Clear();
  1180. mOutFileNames.Clear();
  1181. mTypeDataRefs.Clear();
  1182. mInterfaceSlotRefs.Clear();
  1183. if (rebuildKind == BfModule::RebuildKind_None)
  1184. {
  1185. for (auto& specPair : mSpecializedMethodModules)
  1186. {
  1187. auto specModule = specPair.mValue;
  1188. if (specModule->mIsReified != mIsReified)
  1189. {
  1190. if (mIsReified)
  1191. specModule->ReifyModule();
  1192. else
  1193. specModule->UnreifyModule();
  1194. }
  1195. }
  1196. }
  1197. else
  1198. {
  1199. for (auto& specPair : mSpecializedMethodModules)
  1200. {
  1201. auto specModule = specPair.mValue;
  1202. BfLogSysM("Setting module mIsDeleting %p due to parent module starting a new revision\n", specModule);
  1203. // This module is no longer needed
  1204. specModule->RemoveModuleData();
  1205. specModule->mIsDeleting = true;
  1206. mContext->mDeletingModules.Add(specModule);
  1207. }
  1208. }
  1209. mSpecializedMethodModules.Clear();
  1210. delete mNextAltModule;
  1211. mNextAltModule = NULL;
  1212. BF_ASSERT(mModuleOptions == NULL);
  1213. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1214. bool needsTypePopulated = false;
  1215. int oldOnDemandCount = 0;
  1216. // We don't have to rebuild types in the unspecialized module because there is no
  1217. // data that's needed -- their method instances are all NULL and the module
  1218. // doesn't get included in the build
  1219. if (this != mContext->mScratchModule)
  1220. {
  1221. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1222. {
  1223. auto typeInst = mOwnedTypeInstances[typeIdx];
  1224. if (!typeInst->IsDeleting())
  1225. {
  1226. typeInst->mIsReified = mIsReified;
  1227. if (rebuildKind != BfModule::RebuildKind_None)
  1228. {
  1229. if (typeInst->IsOnDemand())
  1230. {
  1231. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1232. if (rebuildKind == BfModule::RebuildKind_All)
  1233. mContext->DeleteType(typeInst);
  1234. else
  1235. {
  1236. RebuildMethods(typeInst);
  1237. }
  1238. }
  1239. else
  1240. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1241. mContext->RebuildType(typeInst, false, false, true);
  1242. //mContext->RebuildType(typeInst, false, false, false);
  1243. }
  1244. else
  1245. {
  1246. auto _HandleMethod = [&](BfMethodInstance* methodInstance)
  1247. {
  1248. if ((methodInstance != NULL) && (methodInstance->mDeclModule != NULL))
  1249. methodInstance->mDeclModule = this;
  1250. };
  1251. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1252. {
  1253. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1254. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  1255. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  1256. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  1257. {
  1258. oldOnDemandCount++;
  1259. }
  1260. _HandleMethod(methodGroup.mDefault);
  1261. if (methodGroup.mMethodSpecializationMap != NULL)
  1262. for (auto& kv : *methodGroup.mMethodSpecializationMap)
  1263. _HandleMethod(kv.mValue);
  1264. }
  1265. }
  1266. if (typeInst->IsDeleting())
  1267. typeIdx--;
  1268. }
  1269. }
  1270. }
  1271. if (!mIsDeleting)
  1272. Init();
  1273. mOnDemandMethodCount += oldOnDemandCount;
  1274. VerifyOnDemandMethods();
  1275. }
  1276. void BfModule::StartExtension()
  1277. {
  1278. BF_ASSERT(!mIsModuleMutable);
  1279. BfLogSysM("Extension started of module %p\n", this);
  1280. mExtensionCount++;
  1281. if (mBfIRBuilder != NULL)
  1282. mPrevIRBuilders.push_back(mBfIRBuilder);
  1283. mBfIRBuilder = NULL;
  1284. mWantsIRIgnoreWrites = false;
  1285. mFuncReferences.Clear();
  1286. mClassVDataRefs.Clear();
  1287. mClassVDataExtRefs.Clear();
  1288. for (auto& kv : mTypeDataRefs)
  1289. kv.mValue = BfIRValue();
  1290. mDbgRawAllocDataRefs.Clear();
  1291. mStringCharPtrPool.Clear();
  1292. mStringObjectPool.Clear();
  1293. mStaticFieldRefs.Clear();
  1294. for (auto& kv : mInterfaceSlotRefs)
  1295. kv.mValue = BfIRValue();
  1296. for (auto& pairVal : mDeferredMethodCallData)
  1297. delete pairVal.mValue;
  1298. mDeferredMethodCallData.Clear();
  1299. mDeferredMethodIds.Clear();
  1300. DisownMethods();
  1301. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1302. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1303. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1304. Init(false);
  1305. if (!wasAwaitingInitFinish)
  1306. FinishInit();
  1307. mOnDemandMethodCount = prevOnDemandMethodCount;
  1308. }
  1309. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1310. {
  1311. auto hasObjectDebugFlags = mContext->mBfObjectType->mFieldInstances[0].mResolvedType->IsInteger();
  1312. BfIRValue vDataValue;
  1313. if (hasObjectDebugFlags)
  1314. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1315. else
  1316. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1317. typeValueParams.push_back(vDataValue);
  1318. if (hasObjectDebugFlags)
  1319. {
  1320. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1321. typeValueParams.push_back(GetDefaultValue(primType));
  1322. }
  1323. }
  1324. BfIRValue BfModule::GetConstValue(int64 val)
  1325. {
  1326. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1327. }
  1328. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1329. {
  1330. BfType* checkType = type;
  1331. if (type->IsTypedPrimitive())
  1332. {
  1333. checkType = type->GetUnderlyingType();
  1334. }
  1335. if (checkType->IsPrimitiveType())
  1336. {
  1337. auto primType = (BfPrimitiveType*)checkType;
  1338. if (checkType->IsFloat())
  1339. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1340. else
  1341. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1342. }
  1343. return BfIRValue();
  1344. }
  1345. BfIRValue BfModule::GetConstValue8(int val)
  1346. {
  1347. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1348. }
  1349. BfIRValue BfModule::GetConstValue32(int32 val)
  1350. {
  1351. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1352. }
  1353. BfIRValue BfModule::GetConstValue64(int64 val)
  1354. {
  1355. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1356. }
  1357. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1358. {
  1359. PopulateType(type, BfPopulateType_Data);
  1360. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1361. if (type->IsTypedPrimitive())
  1362. {
  1363. auto underlyingType = type->GetUnderlyingType();
  1364. if (underlyingType == NULL)
  1365. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1366. return GetDefaultValue(type->GetUnderlyingType());
  1367. }
  1368. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1369. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1370. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1371. if ((type->IsIntegral()) || (type->IsBoolean()))
  1372. {
  1373. auto primType = (BfPrimitiveType*)type;
  1374. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1375. }
  1376. if (type->IsFloat())
  1377. {
  1378. auto primType = (BfPrimitiveType*)type;
  1379. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1380. }
  1381. return mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(type));
  1382. }
  1383. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1384. {
  1385. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1386. if (type->mSize == 0)
  1387. return BfTypedValue(BfIRValue::sValueless, type);
  1388. else if (mBfIRBuilder != NULL)
  1389. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1390. else
  1391. return BfTypedValue(BfIRValue(BfIRValueFlags_Value, -1), type);
  1392. }
  1393. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1394. {
  1395. if (type->IsVar())
  1396. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1397. PopulateType(type, BfPopulateType_Data);
  1398. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1399. if (defaultValueKind == BfDefaultValueKind_Undef)
  1400. {
  1401. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(type)), type);
  1402. }
  1403. BfTypedValue typedValue;
  1404. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1405. {
  1406. if (type->IsRef())
  1407. {
  1408. BfRefType* refType = (BfRefType*)type;
  1409. BfType* underlyingType = refType->GetUnderlyingType();
  1410. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1411. }
  1412. else
  1413. {
  1414. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1415. }
  1416. if (!mBfIRBuilder->mIgnoreWrites)
  1417. {
  1418. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1419. GetConstValue(type->mSize), type->mAlign);
  1420. }
  1421. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1422. typedValue = LoadValue(typedValue);
  1423. return typedValue;
  1424. }
  1425. if ((type->IsRef()) && (!allowRef))
  1426. {
  1427. BfRefType* refType = (BfRefType*)type;
  1428. BfType* underlyingType = refType->GetUnderlyingType();
  1429. if (underlyingType->IsValuelessType())
  1430. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1431. else
  1432. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1433. }
  1434. else
  1435. {
  1436. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1437. }
  1438. return typedValue;
  1439. }
  1440. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1441. {
  1442. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1443. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1444. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1445. BfIRValue strConstant;
  1446. if (define)
  1447. {
  1448. strConstant = mBfIRBuilder->CreateConstString(str);
  1449. }
  1450. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1451. true, BfIRLinkageType_External,
  1452. strConstant, stringDataName);
  1453. if (define)
  1454. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1455. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1456. }
  1457. void BfModule::FixConstValueParams(BfTypeInstance* typeInst, SizedArrayImpl<BfIRValue>& valueParams, bool fillInPadding)
  1458. {
  1459. if ((!typeInst->mTypeDef->mIsCombinedPartial) && (!fillInPadding))
  1460. return;
  1461. int prevDataIdx = -1;
  1462. int usedDataIdx = 0;
  1463. int valueParamIdx = 0;
  1464. if (typeInst->mBaseType != NULL)
  1465. {
  1466. usedDataIdx++;
  1467. valueParamIdx++;
  1468. prevDataIdx++;
  1469. }
  1470. int startingParamsSize = (int)valueParams.mSize;
  1471. for (int fieldIdx = 0; fieldIdx < (int)typeInst->mFieldInstances.size(); fieldIdx++)
  1472. {
  1473. auto fieldInstance = &typeInst->mFieldInstances[fieldIdx];
  1474. if (fieldInstance->mDataIdx < 0)
  1475. continue;
  1476. BF_ASSERT(fieldInstance->mDataIdx > prevDataIdx);
  1477. if (fillInPadding)
  1478. {
  1479. for (int i = prevDataIdx + 1; i < fieldInstance->mDataIdx; i++)
  1480. valueParams.Insert(valueParamIdx++, mBfIRBuilder->CreateConstArrayZero(0));
  1481. }
  1482. valueParamIdx++;
  1483. prevDataIdx = fieldInstance->mDataIdx;
  1484. usedDataIdx++;
  1485. if (usedDataIdx <= valueParams.mSize)
  1486. continue;
  1487. valueParams.Add(GetDefaultValue(fieldInstance->mResolvedType));
  1488. }
  1489. }
  1490. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1491. {
  1492. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1493. mBfIRBuilder->PopulateType(stringTypeInst);
  1494. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1495. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1496. BfIRValue stringValData;
  1497. if (define)
  1498. {
  1499. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1500. mStringCharPtrPool[stringId] = stringCharsVal;
  1501. SizedArray<BfIRValue, 8> typeValueParams;
  1502. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1503. FixConstValueParams(stringTypeInst->mBaseType, typeValueParams);
  1504. auto objData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1505. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1506. typeValueParams.clear();
  1507. typeValueParams.push_back(objData);
  1508. if (lenByteCount == 4)
  1509. {
  1510. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1511. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1512. }
  1513. else
  1514. {
  1515. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1516. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1517. }
  1518. typeValueParams.push_back(stringCharsVal); // mPtr
  1519. FixConstValueParams(stringTypeInst, typeValueParams);
  1520. stringValData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1521. }
  1522. mBfIRBuilder->PopulateType(stringTypeInst);
  1523. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1524. mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full),
  1525. true,
  1526. BfIRLinkageType_External,
  1527. define ? stringValData : BfIRValue(),
  1528. stringObjName);
  1529. return stringValLiteral;
  1530. }
  1531. bool BfModule::HasStringId(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1532. {
  1533. if (constHolder == NULL)
  1534. constHolder = mBfIRBuilder;
  1535. auto constant = constHolder->GetConstant(constantStr);
  1536. if (constant == NULL)
  1537. return false;
  1538. while (constant->mConstType == BfConstType_BitCast)
  1539. {
  1540. auto constBitCast = (BfConstantBitCast*)constant;
  1541. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1542. }
  1543. if (constant->mTypeCode == BfTypeCode_StringId)
  1544. {
  1545. return true;
  1546. }
  1547. return false;
  1548. }
  1549. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1550. {
  1551. if (constHolder == NULL)
  1552. constHolder = mBfIRBuilder;
  1553. auto constant = constHolder->GetConstant(constantStr);
  1554. if (constant == NULL)
  1555. return -1;
  1556. if ((constant->mTypeCode == BfTypeCode_StringId) || (constant->mTypeCode == BfTypeCode_CharPtr))
  1557. {
  1558. return constant->mInt32;
  1559. }
  1560. while (constant->mConstType == BfConstType_BitCast)
  1561. {
  1562. auto constBitCast = (BfConstantBitCast*)constant;
  1563. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1564. }
  1565. if (constant->mConstType == BfConstType_GEP32_2)
  1566. {
  1567. auto constGEP = (BfConstantGEP32_2*)constant;
  1568. constant = constHolder->GetConstantById(constGEP->mTarget);
  1569. }
  1570. if (constant->mConstType == BfConstType_GlobalVar)
  1571. {
  1572. auto constGV = (BfGlobalVar*)constant;
  1573. const char* strDataPrefix = "__bfStrData";
  1574. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1575. return atoi(constGV->mName + strlen(strDataPrefix));
  1576. const char* strObjPrefix = "__bfStrObj";
  1577. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1578. return atoi(constGV->mName + strlen(strObjPrefix));
  1579. }
  1580. return -1;
  1581. }
  1582. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1583. {
  1584. int strId = GetStringPoolIdx(constantStr, constHolder);
  1585. if (strId != -1)
  1586. {
  1587. auto& entry = mContext->mStringObjectIdMap[strId];
  1588. return &entry.mString;
  1589. }
  1590. return NULL;
  1591. }
  1592. CeDbgState* BfModule::GetCeDbgState()
  1593. {
  1594. if (!mIsComptimeModule)
  1595. return NULL;
  1596. if ((mCompiler->mCeMachine != NULL) && (mCompiler->mCeMachine->mDebugger != NULL))
  1597. return mCompiler->mCeMachine->mDebugger->mCurDbgState;
  1598. return NULL;
  1599. }
  1600. BfIRValue BfModule::GetStringCharPtr(int stringId, bool force)
  1601. {
  1602. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1603. {
  1604. mUnreifiedStringPoolRefs.Add(stringId);
  1605. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, stringId);
  1606. }
  1607. BfIRValue* irValue = NULL;
  1608. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1609. return *irValue;
  1610. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1611. if (!mStringObjectPool.ContainsKey(stringId))
  1612. mStringPoolRefs.Add(stringId);
  1613. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1614. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1615. *irValue = strCharPtrConst;
  1616. return strCharPtrConst;
  1617. }
  1618. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue, bool force)
  1619. {
  1620. if (strValue.IsConst())
  1621. {
  1622. int stringId = GetStringPoolIdx(strValue);
  1623. BF_ASSERT(stringId != -1);
  1624. return GetStringCharPtr(stringId, force);
  1625. }
  1626. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1627. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1628. return charPtr;
  1629. }
  1630. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str, bool force)
  1631. {
  1632. auto result = GetStringCharPtr(GetStringObjectValue(str, force), force);
  1633. if (result.IsConst())
  1634. {
  1635. auto constant = mBfIRBuilder->GetConstant(result);
  1636. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  1637. return mBfIRBuilder->CreateConst(BfTypeCode_CharPtr, constant->mInt32);
  1638. }
  1639. return result;
  1640. }
  1641. BfIRValue BfModule::GetStringObjectValue(int strId, bool define, bool force)
  1642. {
  1643. BfIRValue* objValue;
  1644. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1645. return *objValue;
  1646. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1647. return GetStringObjectValue(stringPoolEntry.mString, define, force);
  1648. }
  1649. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define, bool force)
  1650. {
  1651. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1652. mBfIRBuilder->PopulateType(stringType);
  1653. int strId = mContext->GetStringLiteralId(str);
  1654. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1655. {
  1656. auto refModule = this;
  1657. if ((this == mContext->mUnreifiedModule) && (mCurTypeInstance != NULL))
  1658. refModule = mCurTypeInstance->mModule;
  1659. refModule->mUnreifiedStringPoolRefs.Add(strId);
  1660. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, strId);
  1661. }
  1662. BfIRValue* irValuePtr = NULL;
  1663. if (mStringObjectPool.TryGetValue(strId, &irValuePtr))
  1664. return *irValuePtr;
  1665. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1666. if (!mStringCharPtrPool.ContainsKey(strId))
  1667. mStringPoolRefs.Add(strId);
  1668. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1669. mStringObjectPool[strId] = strObject;
  1670. mStringPoolRefs.Add(strId);
  1671. return strObject;
  1672. }
  1673. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1674. {
  1675. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1676. type,
  1677. true,
  1678. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1679. constant,
  1680. name.c_str());
  1681. return newConst;
  1682. }
  1683. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1684. {
  1685. auto curScope = mCurMethodState->mCurScope;
  1686. if (curScope->mLabelNode != NULL)
  1687. {
  1688. curScope->mLabelNode->ToString(curScope->mLabel);
  1689. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1690. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1691. auto autoComplete = mCompiler->GetAutoComplete();
  1692. if (autoComplete != NULL)
  1693. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1694. }
  1695. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1696. {
  1697. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1698. while (checkScope != NULL)
  1699. {
  1700. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1701. {
  1702. auto errorNode = Warn(0, StrFormat("Duplicate scope label '%s'", checkScope->mLabel.c_str()), curScope->mLabelNode);
  1703. if (errorNode != NULL)
  1704. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1705. break;
  1706. }
  1707. checkScope = checkScope->mPrevScope;
  1708. }
  1709. }
  1710. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1711. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1712. {
  1713. if (prevScope->mHadScopeValueRetain)
  1714. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1715. else
  1716. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1717. }
  1718. mCurMethodState->mBlockNestLevel++;
  1719. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1720. {
  1721. // DIScope could be NULL if we're in an unspecialized method (for example)
  1722. if (mCurMethodState->mCurScope->mDIScope)
  1723. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1724. }
  1725. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1726. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1727. mCurMethodState->mCurScope->mMixinState = mCurMethodState->mMixinState;
  1728. }
  1729. void BfModule::RestoreScoreState_LocalVariables(int localVarStart)
  1730. {
  1731. while (localVarStart < (int)mCurMethodState->mLocals.size())
  1732. {
  1733. auto localVar = mCurMethodState->mLocals.back();
  1734. LocalVariableDone(localVar, false);
  1735. mCurMethodState->mLocals.pop_back();
  1736. if (localVar->mShadowedLocal != NULL)
  1737. {
  1738. BfLocalVarEntry* localVarEntryPtr;
  1739. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1740. {
  1741. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1742. }
  1743. }
  1744. else
  1745. {
  1746. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1747. }
  1748. if (localVar->mIsBumpAlloc)
  1749. localVar->~BfLocalVariable();
  1750. else
  1751. delete localVar;
  1752. }
  1753. }
  1754. void BfModule::RestoreScopeState()
  1755. {
  1756. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1757. mCurMethodState->mBlockNestLevel--;
  1758. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1759. {
  1760. BfIRBlock afterEndBlock;
  1761. if (!mCurMethodState->mLeftBlockUncond)
  1762. {
  1763. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1764. mBfIRBuilder->CreateBr(afterEndBlock);
  1765. mBfIRBuilder->ClearDebugLocation_Last();
  1766. }
  1767. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1768. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1769. if (afterEndBlock)
  1770. {
  1771. mBfIRBuilder->AddBlock(afterEndBlock);
  1772. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1773. }
  1774. }
  1775. mCurMethodState->mCurScope->mDone = true;
  1776. if (!mCurMethodState->mLeftBlockUncond)
  1777. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1778. EmitDeferredCallProcessorInstances(mCurMethodState->mCurScope);
  1779. RestoreScoreState_LocalVariables(mCurMethodState->mCurScope->mLocalVarStart);
  1780. if (mCurMethodState->mCurScope->mValueScopeStart)
  1781. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1782. mCurMethodState->mCurScope = prevScopeData;
  1783. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1784. }
  1785. BfIRValue BfModule::CreateAlloca(BfIRType irType, int align, bool addLifetime, const char* name, BfIRValue arraySize)
  1786. {
  1787. if (mBfIRBuilder->mIgnoreWrites)
  1788. return mBfIRBuilder->GetFakeVal();
  1789. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1790. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1791. if (!mBfIRBuilder->mIgnoreWrites)
  1792. BF_ASSERT(!prevInsertBlock.IsFake());
  1793. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1794. BfIRValue allocaInst;
  1795. if (arraySize)
  1796. allocaInst = mBfIRBuilder->CreateAlloca(irType, arraySize);
  1797. else
  1798. allocaInst = mBfIRBuilder->CreateAlloca(irType);
  1799. if (align > 0)
  1800. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  1801. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1802. if (name != NULL)
  1803. mBfIRBuilder->SetName(allocaInst, name);
  1804. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1805. if ((addLifetime) && (WantsLifetimes()))
  1806. {
  1807. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1808. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1809. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1810. }
  1811. return allocaInst;
  1812. }
  1813. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1814. {
  1815. if (mBfIRBuilder->mIgnoreWrites)
  1816. return mBfIRBuilder->GetFakeVal();
  1817. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1818. mBfIRBuilder->PopulateType(type);
  1819. return CreateAlloca(mBfIRBuilder->MapType(type), type->mAlign, addLifetime, name, arraySize);
  1820. }
  1821. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1822. {
  1823. if (mBfIRBuilder->mIgnoreWrites)
  1824. return mBfIRBuilder->GetFakeVal();
  1825. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1826. mBfIRBuilder->PopulateType(typeInst);
  1827. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1828. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1829. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1830. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1831. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1832. if (name != NULL)
  1833. mBfIRBuilder->SetName(allocaInst, name);
  1834. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1835. if ((addLifetime) && (WantsLifetimes()))
  1836. {
  1837. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1838. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1839. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1840. }
  1841. return allocaInst;
  1842. }
  1843. BfDeferredCallEntry* BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape, BfIRBlock valBlock)
  1844. {
  1845. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1846. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1847. /*if (mCurMethodState->mInHeadScope)
  1848. isScopeAlloc = true;*/
  1849. if (scopeData == NULL)
  1850. return NULL;
  1851. auto checkBaseType = val.mType->ToTypeInstance();
  1852. if ((checkBaseType != NULL) && (checkBaseType->IsObject()) && (!arraySize))
  1853. {
  1854. bool hadDtorCall = false;
  1855. while (checkBaseType != NULL)
  1856. {
  1857. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  1858. if (dtorMethodDef != NULL)
  1859. {
  1860. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  1861. if (dtorMethodInstance)
  1862. {
  1863. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1864. BfIRValue useVal = val.mValue;
  1865. BfIRBlock prevBlock = mBfIRBuilder->GetInsertBlock();
  1866. if (valBlock)
  1867. mBfIRBuilder->SetInsertPoint(valBlock);
  1868. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1869. if (!useVal.IsConst())
  1870. mBfIRBuilder->ClearDebugLocation(useVal);
  1871. if (valBlock)
  1872. mBfIRBuilder->SetInsertPoint(prevBlock);
  1873. if (isDynAlloc)
  1874. {
  1875. //
  1876. }
  1877. else if (condAlloca)
  1878. {
  1879. BF_ASSERT(!IsTargetingBeefBackend());
  1880. BF_ASSERT(!isDynAlloc);
  1881. auto valPtr = CreateAlloca(checkBaseType);
  1882. mBfIRBuilder->ClearDebugLocation_Last();
  1883. mBfIRBuilder->CreateAlignedStore(useVal, valPtr, checkBaseType->mAlign);
  1884. mBfIRBuilder->ClearDebugLocation_Last();
  1885. useVal = valPtr;
  1886. }
  1887. SizedArray<BfIRValue, 1> llvmArgs;
  1888. llvmArgs.push_back(useVal);
  1889. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1890. if (deferredCall != NULL)
  1891. {
  1892. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1893. if (condAlloca)
  1894. deferredCall->mArgsNeedLoad = true;
  1895. }
  1896. hadDtorCall = true;
  1897. break;
  1898. }
  1899. }
  1900. checkBaseType = checkBaseType->mBaseType;
  1901. }
  1902. return NULL;
  1903. }
  1904. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1905. if (mayEscape)
  1906. {
  1907. if ((!IsOptimized()) && (!mIsComptimeModule) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1908. {
  1909. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1910. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1911. if (!isDyn)
  1912. {
  1913. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1914. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1915. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1916. if (!dtorMethodInstance.mMethodInstance)
  1917. {
  1918. Fail(StrFormat("Unable to find %s", methodName));
  1919. }
  1920. else
  1921. {
  1922. SizedArray<BfIRValue, 1> llvmArgs;
  1923. if (IsTargetingBeefBackend())
  1924. {
  1925. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1926. //mBfIRBuilder->ClearDebugLocation_Last();
  1927. }
  1928. else
  1929. llvmArgs.push_back(val.mValue);
  1930. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1931. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1932. if (arraySize)
  1933. llvmArgs.push_back(arraySize);
  1934. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1935. }
  1936. }
  1937. else
  1938. {
  1939. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1940. {
  1941. BfIRValue clearSize = arraySize;
  1942. if (val.mType->GetStride() > 1)
  1943. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1944. const char* methodName = "SetDeletedX";
  1945. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1946. BF_ASSERT(dtorMethodInstance);
  1947. if (!dtorMethodInstance)
  1948. {
  1949. Fail(StrFormat("Unable to find %s", methodName));
  1950. }
  1951. else
  1952. {
  1953. SizedArray<BfIRValue, 1> llvmArgs;
  1954. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1955. //mBfIRBuilder->ClearDebugLocation_Last();
  1956. llvmArgs.push_back(clearSize);
  1957. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1958. }
  1959. }
  1960. else
  1961. {
  1962. intptr clearSize = val.mType->mSize;
  1963. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1964. if (constant != NULL)
  1965. clearSize = (intptr)(clearSize * constant->mInt64);
  1966. const char* funcName = "SetDeleted1";
  1967. if (clearSize >= 16)
  1968. funcName = "SetDeleted16";
  1969. else if (clearSize >= 8)
  1970. funcName = "SetDeleted8";
  1971. else if (clearSize >= 4)
  1972. funcName = "SetDeleted4";
  1973. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1974. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1975. if (!dtorMethodInstance)
  1976. {
  1977. Fail(StrFormat("Unable to find %s", funcName));
  1978. }
  1979. else
  1980. {
  1981. SizedArray<BfIRValue, 1> llvmArgs;
  1982. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1983. //mBfIRBuilder->ClearDebugLocation_Last();
  1984. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1985. }
  1986. }
  1987. }
  1988. }
  1989. }
  1990. return NULL;
  1991. }
  1992. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1993. {
  1994. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1995. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1996. return false;
  1997. auto checkTypeInstance = startTypeInstance;
  1998. while (checkTypeInstance != NULL)
  1999. {
  2000. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  2001. {
  2002. if (fieldInstance.mMergedDataIdx != -1)
  2003. {
  2004. int64 checkMask = 1;
  2005. if (auto fieldTypeInst = fieldInstance.mResolvedType->ToTypeInstance())
  2006. {
  2007. if (fieldTypeInst->IsValueType())
  2008. checkMask = (1 << fieldTypeInst->mMergedFieldDataCount) - 1;
  2009. }
  2010. checkMask <<= fieldInstance.mMergedDataIdx;
  2011. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  2012. {
  2013. // For fields added in extensions, we automatically initialize those if necessary
  2014. auto fieldDef = fieldInstance.GetFieldDef();
  2015. if (!fieldDef->mDeclaringType->IsExtension())
  2016. return false;
  2017. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  2018. {
  2019. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  2020. mBfIRBuilder->SaveDebugLocation();
  2021. if (localVar->IsParam())
  2022. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  2023. else
  2024. {
  2025. BF_ASSERT(localVar->mDeclBlock);
  2026. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  2027. }
  2028. mBfIRBuilder->ClearDebugLocation();
  2029. BfIRValue curVal;
  2030. if (localVar->mIsThis)
  2031. curVal = mBfIRBuilder->GetArgument(0);
  2032. else
  2033. curVal = localVar->mAddr;
  2034. auto subTypeInstance = startTypeInstance;
  2035. while (subTypeInstance != checkTypeInstance)
  2036. {
  2037. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  2038. subTypeInstance = subTypeInstance->mBaseType;
  2039. }
  2040. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  2041. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  2042. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  2043. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  2044. mBfIRBuilder->RestoreDebugLocation();
  2045. }
  2046. localVar->mUnassignedFieldFlags &= ~checkMask;
  2047. if (localVar->mUnassignedFieldFlags == 0)
  2048. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2049. }
  2050. }
  2051. }
  2052. checkTypeInstance = checkTypeInstance->mBaseType;
  2053. }
  2054. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  2055. }
  2056. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  2057. {
  2058. BfAstNode* localNameNode = localVar->mNameNode;
  2059. if ((localVar->mIsThis) && (mCurMethodInstance != NULL))
  2060. {
  2061. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  2062. }
  2063. if (localNameNode != NULL)
  2064. {
  2065. bool isOut = false;
  2066. if (localVar->mResolvedType->IsRef())
  2067. {
  2068. auto refType = (BfRefType*)localVar->mResolvedType;
  2069. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  2070. }
  2071. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  2072. {
  2073. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  2074. TryLocalVariableInit(localVar);
  2075. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  2076. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  2077. // We may have init blocks that we aren't processing here...
  2078. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  2079. deferFullAnalysis = true;
  2080. //bool deferFullAnalysis = true;
  2081. bool deferUsageWarning = deferFullAnalysis && (mCompiler->IsAutocomplete()) &&
  2082. (mCompiler->mResolvePassData->mAutoComplete->mResolveType != BfResolveType_GetFixits);
  2083. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  2084. (!localVar->mIsImplicitParam))
  2085. {
  2086. if (deferUsageWarning)
  2087. {
  2088. // Ignore
  2089. }
  2090. else if (localVar->mIsThis)
  2091. {
  2092. bool foundFields = false;
  2093. auto checkTypeInstance = mCurTypeInstance;
  2094. while (checkTypeInstance != NULL)
  2095. {
  2096. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  2097. {
  2098. if (fieldInstance.mMergedDataIdx == -1)
  2099. continue;
  2100. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  2101. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  2102. {
  2103. auto fieldDef = fieldInstance.GetFieldDef();
  2104. if (mCurMethodInstance->mMethodDef->mDeclaringType->mIsPartial)
  2105. {
  2106. if (mCurMethodInstance->mMethodDef->mDeclaringType != fieldInstance.GetFieldDef()->mDeclaringType)
  2107. {
  2108. // This extension is only responsible for its own fields
  2109. foundFields = true;
  2110. continue;
  2111. }
  2112. if (fieldDef->GetInitializer() != NULL)
  2113. {
  2114. // This initializer was handled in CtorNoBody
  2115. foundFields = true;
  2116. continue;
  2117. }
  2118. }
  2119. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  2120. {
  2121. String propName;
  2122. if (propertyDeclaration->mNameNode != NULL)
  2123. propertyDeclaration->mNameNode->ToString(propName);
  2124. if (checkTypeInstance == mCurTypeInstance)
  2125. {
  2126. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  2127. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2128. }
  2129. else
  2130. {
  2131. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  2132. TypeToString(checkTypeInstance).c_str(),
  2133. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2134. }
  2135. }
  2136. else
  2137. {
  2138. if (checkTypeInstance == mCurTypeInstance)
  2139. {
  2140. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  2141. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2142. }
  2143. else
  2144. {
  2145. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  2146. TypeToString(checkTypeInstance).c_str(),
  2147. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2148. }
  2149. }
  2150. foundFields = true;
  2151. }
  2152. }
  2153. checkTypeInstance = checkTypeInstance->mBaseType;
  2154. }
  2155. if (!foundFields)
  2156. {
  2157. if (mCurTypeInstance->mInstSize > 0)
  2158. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  2159. }
  2160. }
  2161. else if (localVar->IsParam())
  2162. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  2163. else if (!deferUsageWarning)
  2164. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2165. }
  2166. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  2167. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2168. }
  2169. }
  2170. }
  2171. void BfModule::CreateRetValLocal()
  2172. {
  2173. if (mCurMethodState->mRetVal)
  2174. {
  2175. BfLocalVariable* localDef = new BfLocalVariable();
  2176. localDef->mName = "return";
  2177. localDef->mResolvedType = mCurMethodState->mRetVal.mType;
  2178. localDef->mAddr = mCurMethodState->mRetVal.mValue;
  2179. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2180. AddLocalVariableDef(localDef);
  2181. }
  2182. else if (mCurMethodState->mRetValAddr)
  2183. {
  2184. BfLocalVariable* localDef = new BfLocalVariable();
  2185. localDef->mName = "return";
  2186. localDef->mResolvedType = CreateRefType(mCurMethodInstance->mReturnType);
  2187. localDef->mAddr = mCurMethodState->mRetValAddr;
  2188. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2189. AddLocalVariableDef(localDef);
  2190. }
  2191. }
  2192. void BfModule::MarkDynStack(BfScopeData* scopeData)
  2193. {
  2194. auto checkScope = mCurMethodState->mCurScope;
  2195. while (true)
  2196. {
  2197. if (checkScope == scopeData)
  2198. break;
  2199. checkScope->mHadOuterDynStack = true;
  2200. checkScope = checkScope->mPrevScope;
  2201. }
  2202. }
  2203. void BfModule::SaveStackState(BfScopeData* scopeData)
  2204. {
  2205. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  2206. // scopes within scopeData restore the stack
  2207. auto checkScope = mCurMethodState->mCurScope;
  2208. while (true)
  2209. {
  2210. if (checkScope == scopeData)
  2211. {
  2212. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  2213. {
  2214. if (mBfIRBuilder->mHasDebugInfo)
  2215. mBfIRBuilder->SaveDebugLocation();
  2216. auto prevPos = mBfIRBuilder->GetInsertBlock();
  2217. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  2218. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  2219. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  2220. mBfIRBuilder->SetInsertPoint(prevPos);
  2221. if (mBfIRBuilder->mHasDebugInfo)
  2222. mBfIRBuilder->RestoreDebugLocation();
  2223. }
  2224. break;
  2225. }
  2226. if (checkScope->mSavedStack)
  2227. {
  2228. for (auto usage : checkScope->mSavedStackUses)
  2229. mBfIRBuilder->EraseInstFromParent(usage);
  2230. checkScope->mSavedStackUses.Clear();
  2231. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  2232. checkScope->mSavedStack = BfIRValue();
  2233. }
  2234. checkScope = checkScope->mPrevScope;
  2235. }
  2236. }
  2237. BfIRValue BfModule::ValueScopeStart()
  2238. {
  2239. if (IsTargetingBeefBackend())
  2240. return mBfIRBuilder->CreateValueScopeStart();
  2241. return BfIRValue();
  2242. }
  2243. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  2244. {
  2245. if (valueScopeStart)
  2246. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  2247. }
  2248. BfProjectSet* BfModule::GetVisibleProjectSet()
  2249. {
  2250. if (mCurMethodState == NULL)
  2251. return NULL;
  2252. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  2253. {
  2254. HashSet<BfType*> seenTypes;
  2255. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  2256. {
  2257. if (mCurMethodState->mVisibleProjectSet.Add(project))
  2258. {
  2259. for (auto dep : project->mDependencies)
  2260. _AddProject(dep);
  2261. }
  2262. };
  2263. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  2264. {
  2265. auto typeInstance = type->ToTypeInstance();
  2266. if (typeInstance == NULL)
  2267. {
  2268. if (type->IsSizedArray())
  2269. _AddType(type->GetUnderlyingType());
  2270. return;
  2271. }
  2272. if (typeInstance->IsTuple())
  2273. {
  2274. for (auto& fieldInst : typeInstance->mFieldInstances)
  2275. {
  2276. if (fieldInst.mDataIdx != -1)
  2277. _AddType(fieldInst.mResolvedType);
  2278. }
  2279. }
  2280. _AddProject(typeInstance->mTypeDef->mProject);
  2281. if (typeInstance->mGenericTypeInfo == NULL)
  2282. return;
  2283. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2284. {
  2285. if (seenTypes.Add(type))
  2286. _AddType(type);
  2287. }
  2288. };
  2289. if (mCurTypeInstance != NULL)
  2290. {
  2291. _AddType(mCurTypeInstance);
  2292. if ((mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mType == mCurTypeInstance))
  2293. {
  2294. if (mContext->mCurTypeState->mCurTypeDef != NULL)
  2295. _AddProject(mContext->mCurTypeState->mCurTypeDef->mProject);
  2296. }
  2297. }
  2298. auto methodState = mCurMethodState;
  2299. while (methodState != NULL)
  2300. {
  2301. if (methodState->mMethodInstance != NULL)
  2302. {
  2303. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  2304. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  2305. {
  2306. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2307. _AddType(type);
  2308. }
  2309. }
  2310. methodState = methodState->mPrevMethodState;
  2311. }
  2312. }
  2313. return &mCurMethodState->mVisibleProjectSet;
  2314. }
  2315. bool BfModule::IsProjectVisible(BfProject* project)
  2316. {
  2317. auto visibleProjectSet = GetVisibleProjectSet();
  2318. if (visibleProjectSet != NULL)
  2319. return visibleProjectSet->Contains(project);
  2320. auto activeTypeDef = GetActiveTypeDef();
  2321. if (activeTypeDef != NULL)
  2322. {
  2323. if (activeTypeDef->mProject == project)
  2324. return true;
  2325. return activeTypeDef->mProject->HasDependency(project);
  2326. }
  2327. return false;
  2328. }
  2329. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2330. {
  2331. auto bfParser = astNode->GetSourceData()->ToParserData();
  2332. if (bfParser == NULL)
  2333. return NULL;
  2334. BfFileInstance** fileInstancePtr = NULL;
  2335. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2336. {
  2337. return *fileInstancePtr;
  2338. }
  2339. else
  2340. {
  2341. // It's possible two parsers have the same file name (ie: mNextRevision)
  2342. BfFileInstance** namedFileInstancePtr = NULL;
  2343. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2344. {
  2345. auto bfFileInstance = *namedFileInstancePtr;
  2346. *fileInstancePtr = bfFileInstance;
  2347. return bfFileInstance;
  2348. }
  2349. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2350. auto bfFileInstance = new BfFileInstance();
  2351. *fileInstancePtr = bfFileInstance;
  2352. *namedFileInstancePtr = bfFileInstance;
  2353. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2354. bfFileInstance->mParser = bfParser;
  2355. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2356. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasLineInfo()))
  2357. {
  2358. String fileName = bfParser->mFileName;
  2359. for (int i = 0; i < (int)fileName.length(); i++)
  2360. {
  2361. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2362. fileName[i] = DIR_SEP_CHAR;
  2363. }
  2364. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, BF_MAX(slashPos, 0)), bfParser->mMD5Hash);
  2365. }
  2366. return bfFileInstance;
  2367. }
  2368. }
  2369. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2370. {
  2371. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2372. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2373. return;
  2374. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2375. if (astNode == NULL)
  2376. return;
  2377. auto bfParser = astNode->GetSourceData()->ToParserData();
  2378. if (bfParser == NULL)
  2379. return;
  2380. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2381. {
  2382. if (mCurFilePosition.mFileInstance != NULL)
  2383. {
  2384. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2385. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2386. }
  2387. auto bfFileInstance = GetFileFromNode(astNode);
  2388. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2389. {
  2390. mCurFilePosition = bfFileInstance->mPrevPosition;
  2391. }
  2392. else
  2393. {
  2394. mCurFilePosition.mFileInstance = bfFileInstance;
  2395. mCurFilePosition.mCurLine = 0;
  2396. mCurFilePosition.mCurColumn = 0;
  2397. mCurFilePosition.mCurSrcPos = 0;
  2398. }
  2399. }
  2400. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2401. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2402. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2403. if (jumpEntry->mCharIdx > srcPos)
  2404. jumpEntry--;
  2405. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2406. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2407. mCurFilePosition.mCurColumn = 0;
  2408. while (mCurFilePosition.mCurSrcPos < srcPos)
  2409. {
  2410. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2411. {
  2412. mCurFilePosition.mCurLine++;
  2413. mCurFilePosition.mCurColumn = 0;
  2414. }
  2415. else
  2416. {
  2417. mCurFilePosition.mCurColumn++;
  2418. }
  2419. mCurFilePosition.mCurSrcPos++;
  2420. }
  2421. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2422. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasLineInfo()) && (mCurMethodState != NULL))
  2423. {
  2424. int column = mCurFilePosition.mCurColumn + 1;
  2425. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2426. {
  2427. // Set to illegal position
  2428. column = 0;
  2429. }
  2430. if (mSetIllegalSrcPosition)
  2431. column = 0;
  2432. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2433. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2434. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2435. {
  2436. // This is from a different scope...
  2437. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2438. {
  2439. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2440. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2441. }
  2442. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2443. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2444. }
  2445. else
  2446. {
  2447. if (mCurMethodState->mCurScope->mAltDIFile)
  2448. {
  2449. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2450. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2451. }
  2452. }
  2453. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2454. if (mCurMethodState->mCrossingMixin)
  2455. inlineAt = BfIRMDNode();
  2456. if ((!useDIScope) && (mIsComptimeModule))
  2457. useDIScope = wantDIFile;
  2458. if (!useDIScope)
  2459. mBfIRBuilder->ClearDebugLocation();
  2460. else
  2461. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2462. if ((flags & BfSrcPosFlag_Expression) == 0)
  2463. mBfIRBuilder->CreateStatementStart();
  2464. }
  2465. }
  2466. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2467. {
  2468. // We've turned off expr src pos (for now?)
  2469. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2470. }
  2471. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2472. {
  2473. if (mCompiler->mBfObjectTypeDef != NULL)
  2474. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2475. SetIllegalSrcPos();
  2476. }
  2477. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2478. {
  2479. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2480. {
  2481. auto curScope = mCurMethodState->mCurScope->mDIScope;
  2482. if (curScope)
  2483. {
  2484. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2485. {
  2486. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2487. mBfIRBuilder->SetCurrentDebugLocation(0, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2488. }
  2489. else
  2490. {
  2491. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2492. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2493. }
  2494. }
  2495. if ((flags & BfSrcPosFlag_Expression) == 0)
  2496. mBfIRBuilder->CreateStatementStart();
  2497. }
  2498. }
  2499. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2500. {
  2501. // We've turned off expr src pos (for now?)
  2502. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2503. }
  2504. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2505. {
  2506. if ((protection == BfProtection_Public) ||
  2507. (((protection == BfProtection_Protected) || (protection == BfProtection_ProtectedInternal)) && (allowProtected)) ||
  2508. ((protection == BfProtection_Private) && (allowPrivate)))
  2509. return true;
  2510. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2511. {
  2512. mAttributeState->mUsed = true;
  2513. return true;
  2514. }
  2515. if (((protection == BfProtection_Internal) || (protection == BfProtection_ProtectedInternal)) && (checkType != NULL))
  2516. {
  2517. if (CheckInternalProtection(checkType))
  2518. return true;
  2519. }
  2520. return false;
  2521. }
  2522. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2523. {
  2524. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2525. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2526. {
  2527. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2528. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2529. }
  2530. allowProtected = allowPrivate;
  2531. }
  2532. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2533. {
  2534. if ((memberOwner != NULL) && (mCurMethodState != NULL) && (mCurMethodState->mPrivateTypeInstance == memberOwner))
  2535. return true;
  2536. if (memberProtection == BfProtection_Hidden)
  2537. return false;
  2538. if (memberProtection == BfProtection_Public)
  2539. return true;
  2540. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2541. {
  2542. BfTypeInstance* curCheckType = mCurTypeInstance;
  2543. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2544. {
  2545. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2546. curCheckType = mixinOwner;
  2547. }
  2548. bool allowPrivate = (curCheckType != NULL) && (memberOwner->IsInstanceOf(curCheckType->mTypeDef));
  2549. if (curCheckType != NULL)
  2550. {
  2551. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2552. if (memberOwner->mTypeDef->IsGlobalsContainer())
  2553. allowPrivate |= curCheckType->mTypeDef->mNamespace == memberOwner->mTypeDef->mNamespace;
  2554. }
  2555. if (allowPrivate)
  2556. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2557. else
  2558. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2559. }
  2560. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2561. return true;
  2562. if ((memberProtection == BfProtection_Protected) || (memberProtection == BfProtection_ProtectedInternal))
  2563. {
  2564. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2565. {
  2566. bool allowProtected = false;
  2567. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2568. auto curCheckType = mCurTypeInstance;
  2569. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2570. {
  2571. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2572. curCheckType = mixinOwner;
  2573. }
  2574. if ((flags & BfProtectionCheckFlag_InstanceLookup) != 0)
  2575. {
  2576. auto lookupCheckType = lookupStartType;
  2577. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2578. {
  2579. if (lookupCheckType == curCheckType)
  2580. {
  2581. allowProtected = true;
  2582. break;
  2583. }
  2584. if (lookupCheckType == memberOwner)
  2585. break;
  2586. lookupCheckType = lookupCheckType->mBaseType;
  2587. if (lookupCheckType == NULL)
  2588. break;
  2589. }
  2590. }
  2591. else
  2592. {
  2593. auto lookupCheckType = curCheckType;
  2594. while (lookupCheckType->mInheritDepth >= memberOwner->mInheritDepth)
  2595. {
  2596. if (lookupCheckType == memberOwner)
  2597. {
  2598. allowProtected = true;
  2599. break;
  2600. }
  2601. lookupCheckType = lookupCheckType->mBaseType;
  2602. if (lookupCheckType == NULL)
  2603. break;
  2604. }
  2605. }
  2606. if (!allowProtected)
  2607. {
  2608. // It's possible our outer type is derived from 'memberOwner'
  2609. while (curCheckType->mTypeDef->mNestDepth > 0)
  2610. {
  2611. curCheckType = GetOuterType(curCheckType);
  2612. if (curCheckType == NULL)
  2613. break;
  2614. auto lookupCheckType = lookupStartType;
  2615. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2616. {
  2617. if (lookupCheckType == curCheckType)
  2618. {
  2619. allowProtected = true;
  2620. break;
  2621. }
  2622. if (lookupCheckType == memberOwner)
  2623. break;
  2624. lookupCheckType = lookupCheckType->mBaseType;
  2625. if (lookupCheckType == NULL)
  2626. break;
  2627. }
  2628. }
  2629. }
  2630. if (allowProtected)
  2631. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2632. else
  2633. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2634. }
  2635. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2636. return true;
  2637. }
  2638. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2639. {
  2640. mAttributeState->mUsed = true;
  2641. return true;
  2642. }
  2643. if (((memberProtection == BfProtection_Internal) || (memberProtection == BfProtection_ProtectedInternal)) && (memberOwner != NULL))
  2644. {
  2645. if (CheckInternalProtection(memberOwner->mTypeDef))
  2646. return true;
  2647. }
  2648. return false;
  2649. }
  2650. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2651. {
  2652. if (mCompiler->mResolvePassData != NULL)
  2653. {
  2654. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2655. sourceClassifier->SetElementType(astNode, elementType);
  2656. }
  2657. }
  2658. void BfModule::SetHighestElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2659. {
  2660. if (mCompiler->mResolvePassData != NULL)
  2661. {
  2662. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2663. sourceClassifier->SetHighestElementType(astNode, elementType);
  2664. }
  2665. }
  2666. bool BfModule::PreFail()
  2667. {
  2668. if (!mIgnoreErrors)
  2669. return true;
  2670. SetFail();
  2671. return false;
  2672. }
  2673. void BfModule::SetFail()
  2674. {
  2675. if (mIgnoreErrors)
  2676. {
  2677. if (mAttributeState != NULL)
  2678. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2679. }
  2680. }
  2681. void BfModule::VerifyOnDemandMethods()
  2682. {
  2683. #ifdef _DEBUG
  2684. // if (mParentModule != NULL)
  2685. // {
  2686. // BF_ASSERT(mOnDemandMethodCount == 0);
  2687. // mParentModule->VerifyOnDemandMethods();
  2688. // return;
  2689. // }
  2690. //
  2691. // int onDemandCount = 0;
  2692. // for (auto type : mOwnedTypeInstances)
  2693. // {
  2694. // auto typeInst = type->ToTypeInstance();
  2695. // for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  2696. // {
  2697. // if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  2698. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  2699. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  2700. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  2701. // onDemandCount++;
  2702. // }
  2703. // }
  2704. //
  2705. // BF_ASSERT(mOnDemandMethodCount == onDemandCount);
  2706. #endif
  2707. }
  2708. bool BfModule::IsSkippingExtraResolveChecks()
  2709. {
  2710. if (mIsComptimeModule)
  2711. return false;
  2712. return mCompiler->IsSkippingExtraResolveChecks();
  2713. }
  2714. bool BfModule::AddErrorContext(StringImpl& errorString, BfAstNode* refNode, BfWhileSpecializingFlags& isWhileSpecializing, bool isWarning)
  2715. {
  2716. bool isWhileSpecializingMethod = false;
  2717. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2718. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2719. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2720. errorString += StrFormat("\n while generating append size calculating method");
  2721. else if (refNode == NULL)
  2722. {
  2723. if (mCurTypeInstance != NULL)
  2724. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2725. else if (mProject != NULL)
  2726. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2727. }
  2728. if (mCurTypeInstance != NULL)
  2729. {
  2730. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2731. {
  2732. // Propogate the fail all the way to the main method (assuming we're in a local method or lambda)
  2733. if (isWarning)
  2734. methodInstance->mHasWarning = true;
  2735. else
  2736. methodInstance->mHasFailed = true;
  2737. if (!methodInstance->mHasStartedDeclaration)
  2738. StartMethodDeclaration(methodInstance, NULL);
  2739. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2740. if (isSpecializedMethod)
  2741. {
  2742. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2743. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2744. if (unspecializedMethod == methodInstance)
  2745. {
  2746. // This is a local method inside a generic method
  2747. BF_ASSERT(methodInstance->mMethodDef->mIsLocalMethod);
  2748. }
  2749. else
  2750. {
  2751. if (isWarning)
  2752. {
  2753. if (unspecializedMethod->mHasWarning)
  2754. return false; // At least SOME error has already been reported
  2755. }
  2756. else
  2757. {
  2758. if (unspecializedMethod->mHasFailed)
  2759. return false; // At least SOME error has already been reported
  2760. }
  2761. }
  2762. }
  2763. if (isSpecializedMethod)
  2764. {
  2765. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2766. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2767. isWhileSpecializingMethod = true;
  2768. }
  2769. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2770. {
  2771. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2772. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2773. isWhileSpecializingMethod = true;
  2774. }
  2775. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2776. {
  2777. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2778. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2779. }
  2780. return true;
  2781. };
  2782. bool hadMethodInstance = false;
  2783. if (mCurMethodState != NULL)
  2784. {
  2785. auto checkMethodState = mCurMethodState;
  2786. while (checkMethodState != NULL)
  2787. {
  2788. auto methodInstance = checkMethodState->mMethodInstance;
  2789. if (methodInstance == NULL)
  2790. {
  2791. checkMethodState = checkMethodState->mPrevMethodState;
  2792. continue;
  2793. }
  2794. hadMethodInstance = true;
  2795. if (!_CheckMethodInstance(methodInstance))
  2796. return false;
  2797. checkMethodState = checkMethodState->mPrevMethodState;
  2798. }
  2799. }
  2800. if ((!hadMethodInstance) && (mCurMethodInstance != NULL))
  2801. {
  2802. if (!_CheckMethodInstance(mCurMethodInstance))
  2803. return false;
  2804. }
  2805. }
  2806. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2807. {
  2808. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2809. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2810. }
  2811. return true;
  2812. }
  2813. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent, bool deferError)
  2814. {
  2815. BP_ZONE("BfModule::Fail");
  2816. if (mIgnoreErrors)
  2817. {
  2818. mHadIgnoredError = true;
  2819. if (mAttributeState != NULL)
  2820. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2821. return NULL;
  2822. }
  2823. if (!mReportErrors)
  2824. {
  2825. mCompiler->mPassInstance->SilentFail();
  2826. return NULL;
  2827. }
  2828. if (refNode != NULL)
  2829. refNode = BfNodeToNonTemporary(refNode);
  2830. //BF_ASSERT(refNode != NULL);
  2831. if (mIsComptimeModule)
  2832. {
  2833. if (auto ceDbgState = GetCeDbgState())
  2834. {
  2835. // Follow normal fail path
  2836. }
  2837. else
  2838. {
  2839. mHadBuildError = true;
  2840. if ((mCompiler->mCeMachine->mCurContext != NULL) && (mCompiler->mCeMachine->mCurContext->mCurCallSource != NULL) &&
  2841. (mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode != NULL))
  2842. {
  2843. BfError* bfError = mCompiler->mPassInstance->Fail("Comptime method generation had errors",
  2844. mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode);
  2845. if (bfError != NULL)
  2846. mCompiler->mPassInstance->MoreInfo(error, refNode);
  2847. return bfError;
  2848. }
  2849. return NULL;
  2850. }
  2851. }
  2852. if ((mCurMethodState != NULL) && (mCurMethodState->mConstResolveState != NULL) && (mCurMethodState->mConstResolveState->mInCalcAppend))
  2853. {
  2854. mCurMethodState->mConstResolveState->mFailed = true;
  2855. return NULL;
  2856. }
  2857. if (mCurMethodInstance != NULL)
  2858. mCurMethodInstance->mHasFailed = true;
  2859. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2860. return NULL;
  2861. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2862. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2863. if (!mHadBuildError)
  2864. mHadBuildError = true;
  2865. if (mParentModule != NULL)
  2866. mParentModule->mHadBuildError = true;
  2867. if (mCurTypeInstance != NULL)
  2868. AddFailType(mCurTypeInstance);
  2869. BfLogSysM("BfModule::Fail module %p type %p %s @ %s\n", this, mCurTypeInstance, error.c_str(), (refNode != NULL) ? refNode->LocationToString().c_str() : "???");
  2870. String errorString = error;
  2871. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2872. if (!AddErrorContext(errorString, refNode, isWhileSpecializing, false))
  2873. return NULL;
  2874. BfError* bfError = NULL;
  2875. if (isWhileSpecializing)
  2876. deferError = true;
  2877. if (!mHadBuildError)
  2878. mHadBuildError = true;
  2879. // Check mixins
  2880. {
  2881. auto checkMethodState = mCurMethodState;
  2882. while (checkMethodState != NULL)
  2883. {
  2884. auto rootMixinState = checkMethodState->GetRootMixinState();
  2885. if (rootMixinState != NULL)
  2886. {
  2887. String mixinErr = StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str());
  2888. if (deferError)
  2889. bfError = mCompiler->mPassInstance->DeferFail(mixinErr, rootMixinState->mSource);
  2890. else
  2891. bfError = mCompiler->mPassInstance->Fail(mixinErr, rootMixinState->mSource);
  2892. if (bfError == NULL)
  2893. return NULL;
  2894. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2895. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2896. auto mixinState = checkMethodState->mMixinState;
  2897. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2898. {
  2899. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2900. mixinState = mixinState->mPrevMixinState;
  2901. }
  2902. return bfError;
  2903. }
  2904. checkMethodState = checkMethodState->mPrevMethodState;
  2905. }
  2906. }
  2907. if (deferError)
  2908. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2909. else if (refNode == NULL)
  2910. bfError = mCompiler->mPassInstance->Fail(errorString);
  2911. else
  2912. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2913. if (bfError != NULL)
  2914. {
  2915. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2916. bfError->mProject = mProject;
  2917. bfError->mIsPersistent = isPersistent;
  2918. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2919. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2920. else if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2921. mCompiler->mPassInstance->MoreInfo("Error in emitted code", mCurMethodState->mEmitRefNode);
  2922. }
  2923. return bfError;
  2924. }
  2925. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2926. {
  2927. if (mHadBuildError)
  2928. return NULL;
  2929. return Fail(error, refNode);
  2930. }
  2931. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2932. {
  2933. if (mIgnoreErrors)
  2934. return NULL;
  2935. if (refNode != NULL)
  2936. refNode = BfNodeToNonTemporary(refNode);
  2937. mHadBuildError = true;
  2938. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2939. if (bfError != NULL)
  2940. bfError->mProject = mProject;
  2941. return bfError;
  2942. }
  2943. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent, bool showInSpecialized)
  2944. {
  2945. if (mIgnoreErrors || mIgnoreWarnings)
  2946. return NULL;
  2947. if (!mReportErrors)
  2948. {
  2949. mCompiler->mPassInstance->SilentFail();
  2950. return NULL;
  2951. }
  2952. BfAstNode* unwarnNode = refNode;
  2953. //
  2954. {
  2955. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2956. while (parentNodeEntry != NULL)
  2957. {
  2958. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2959. break;
  2960. unwarnNode = parentNodeEntry->mNode;
  2961. parentNodeEntry = parentNodeEntry->mPrev;
  2962. }
  2963. }
  2964. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2965. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2966. {
  2967. return NULL;
  2968. }
  2969. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2970. if (mCurMethodInstance != NULL)
  2971. {
  2972. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2973. {
  2974. if (!showInSpecialized)
  2975. return NULL;
  2976. }
  2977. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2978. return NULL; // No ctorCalcAppend warnings
  2979. }
  2980. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2981. {
  2982. if (!showInSpecialized)
  2983. return NULL;
  2984. }
  2985. if (refNode != NULL)
  2986. refNode = BfNodeToNonTemporary(refNode);
  2987. String warningString = warning;
  2988. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2989. if (!AddErrorContext(warningString, refNode, isWhileSpecializing, true))
  2990. return NULL;
  2991. bool deferWarning = isWhileSpecializing != BfWhileSpecializingFlag_None;
  2992. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2993. {
  2994. // We used to bubble up warnings into the mixin injection site, BUT
  2995. // we are now assuming any relevant warnings will be given at the declaration site
  2996. return NULL;
  2997. }
  2998. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2999. {
  3000. BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Emitted code had errors", mCurMethodState->mEmitRefNode);
  3001. if (bfError != NULL)
  3002. mCompiler->mPassInstance->MoreInfo(warningString, refNode);
  3003. return bfError;
  3004. }
  3005. BfError* bfError;
  3006. if (refNode != NULL)
  3007. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warningString, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  3008. else
  3009. bfError = mCompiler->mPassInstance->Warn(warningNum, warningString);
  3010. if (bfError != NULL)
  3011. {
  3012. bfError->mIsWhileSpecializing = isWhileSpecializing;
  3013. bfError->mProject = mProject;
  3014. AddFailType(mCurTypeInstance);
  3015. mHadBuildWarning = true;
  3016. bfError->mIsPersistent = isPersistent;
  3017. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  3018. {
  3019. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  3020. if (parser != NULL)
  3021. {
  3022. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  3023. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  3024. if (warningNum != 0)
  3025. {
  3026. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  3027. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  3028. }
  3029. }
  3030. }
  3031. }
  3032. return bfError;
  3033. }
  3034. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfFieldInstance* fieldInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  3035. {
  3036. if (customAttributes == NULL)
  3037. return;
  3038. auto _AddDeclarationMoreInfo = [&]()
  3039. {
  3040. if (methodInstance != NULL)
  3041. {
  3042. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  3043. mCompiler->mPassInstance->MoreInfo(
  3044. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  3045. methodInstance->mMethodDef->GetRefNode());
  3046. }
  3047. else
  3048. {
  3049. mCompiler->mPassInstance->MoreInfo(
  3050. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  3051. typeInstance->mTypeDef->GetRefNode());
  3052. }
  3053. };
  3054. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  3055. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  3056. if ((customAttribute != NULL) && (targetSrc != NULL))
  3057. {
  3058. String err;
  3059. if (fieldInstance != NULL)
  3060. err = StrFormat("'%s' is obsolete", FieldToString(fieldInstance).c_str());
  3061. else if (methodInstance != NULL)
  3062. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  3063. else
  3064. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3065. bool isError = false;
  3066. if (customAttribute->mCtorArgs.size() >= 1)
  3067. {
  3068. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  3069. if (constant->mTypeCode == BfTypeCode_Boolean)
  3070. {
  3071. isError = constant->mBool;
  3072. }
  3073. else if (constant->mTypeCode == BfTypeCode_StringId)
  3074. {
  3075. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3076. if (str != NULL)
  3077. {
  3078. err += ":\n '";
  3079. err += *str;
  3080. err += "'";
  3081. }
  3082. if (customAttribute->mCtorArgs.size() >= 2)
  3083. {
  3084. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  3085. isError = constant->mBool;
  3086. }
  3087. }
  3088. }
  3089. BfError* error = NULL;
  3090. if (isError)
  3091. error = Fail(err, targetSrc);
  3092. else
  3093. error = Warn(0, err, targetSrc, false, true);
  3094. if (error != NULL)
  3095. _AddDeclarationMoreInfo();
  3096. }
  3097. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  3098. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3099. {
  3100. String err;
  3101. if (fieldInstance != NULL)
  3102. err += StrFormat("Method error: '", FieldToString(fieldInstance).c_str());
  3103. else if (methodInstance != NULL)
  3104. err += StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  3105. else
  3106. err += StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3107. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3108. if (str != NULL)
  3109. err += *str;
  3110. err += "'";
  3111. if (Fail(err, targetSrc) != NULL)
  3112. _AddDeclarationMoreInfo();
  3113. }
  3114. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  3115. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  3116. {
  3117. String err;
  3118. if (fieldInstance != NULL)
  3119. err += StrFormat("Field warning: '", FieldToString(fieldInstance).c_str());
  3120. else if (methodInstance != NULL)
  3121. err += StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  3122. else
  3123. err += StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3124. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3125. if (str != NULL)
  3126. err += *str;
  3127. err += "'";
  3128. if (Warn(0, err, targetSrc, false, true) != NULL)
  3129. _AddDeclarationMoreInfo();
  3130. }
  3131. }
  3132. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  3133. {
  3134. if (mBfIRBuilder->mOpFailed)
  3135. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  3136. }
  3137. void BfModule::FatalError(const StringImpl& error, const char* file, int line, int column)
  3138. {
  3139. static bool sHadFatalError = false;
  3140. static bool sHadReentrancy = false;
  3141. if (sHadFatalError)
  3142. {
  3143. return;
  3144. sHadReentrancy = true;
  3145. }
  3146. sHadFatalError = true;
  3147. String fullError = error;
  3148. if (file != NULL)
  3149. {
  3150. fullError += StrFormat(" at %s:%d", file, line);
  3151. if (column != -1)
  3152. fullError += StrFormat(":%d", column);
  3153. }
  3154. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3155. if (mCurTypeInstance != NULL)
  3156. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3157. if (mCurMethodInstance != NULL)
  3158. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3159. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3160. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3161. if (sHadReentrancy)
  3162. fullError += "\nError had reentrancy";
  3163. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  3164. }
  3165. void BfModule::FatalError(const StringImpl& error, BfFailHandleKind failHandleKind)
  3166. {
  3167. if (failHandleKind == BfFailHandleKind_Normal)
  3168. FatalError(error);
  3169. else if (failHandleKind == BfFailHandleKind_Soft)
  3170. InternalError(error);
  3171. }
  3172. void BfModule::InternalError(const StringImpl& error, BfAstNode* refNode, const char* file, int line)
  3173. {
  3174. static bool isInside = false;
  3175. if (isInside)
  3176. return;
  3177. isInside = true;
  3178. String fullError = error;
  3179. if (file != NULL)
  3180. fullError += StrFormat(" at %s:%d", file, line);
  3181. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3182. if (mCurTypeInstance != NULL)
  3183. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3184. if (mCurMethodInstance != NULL)
  3185. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3186. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3187. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3188. Fail(String("INTERNAL ERROR: ") + fullError, refNode);
  3189. isInside = false;
  3190. }
  3191. void BfModule::NotImpl(BfAstNode* astNode)
  3192. {
  3193. Fail("INTERNAL ERROR: Not implemented", astNode);
  3194. }
  3195. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  3196. {
  3197. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  3198. if (!allowPrivate)
  3199. allowPrivate |= memberType->IsInterface();
  3200. bool allowProtected = allowPrivate;
  3201. //TODO: We had this commented out, but this makes accessing protected properties fail
  3202. if (mCurTypeInstance != NULL)
  3203. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  3204. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  3205. {
  3206. return false;
  3207. }
  3208. return true;
  3209. }
  3210. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  3211. {
  3212. auto memberTypeInstance = memberType->ToTypeInstance();
  3213. if (memberTypeInstance == NULL)
  3214. {
  3215. auto underlyingType = memberType->GetUnderlyingType();
  3216. if (underlyingType != NULL)
  3217. return CheckDefineMemberProtection(protection, underlyingType);
  3218. return true;
  3219. }
  3220. if (memberTypeInstance->mTypeDef->mProtection < protection)
  3221. {
  3222. // Check for any definition up to the actual declared member type
  3223. auto commonOuterType = FindCommonOuterType(memberTypeInstance->mTypeDef, mCurTypeInstance->mTypeDef);
  3224. if (commonOuterType == memberTypeInstance->mTypeDef)
  3225. commonOuterType = commonOuterType->mOuterType;
  3226. auto checkTypeDef = mCurTypeInstance->mTypeDef;
  3227. while ((checkTypeDef != NULL) && (checkTypeDef != commonOuterType))
  3228. {
  3229. protection = std::min(protection, checkTypeDef->mProtection);
  3230. checkTypeDef = checkTypeDef->mOuterType;
  3231. }
  3232. }
  3233. if (memberTypeInstance->mTypeDef->mProtection < protection)
  3234. return false;
  3235. if (memberTypeInstance->IsGenericTypeInstance())
  3236. {
  3237. // When we're a generic struct, our data layout can depend on our generic parameters as well
  3238. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  3239. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3240. {
  3241. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  3242. return false;
  3243. }
  3244. }
  3245. return true;
  3246. }
  3247. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags, BfDepContext* depContext)
  3248. {
  3249. if (usedType == userType)
  3250. return;
  3251. if (((flags & BfDependencyMap::DependencyFlag_ConstValue) != 0) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_FieldType))
  3252. {
  3253. // This can be an `int32[UsedType.cVal]` type reference
  3254. flags = (BfDependencyMap::DependencyFlags)(flags | BfDependencyMap::DependencyFlag_ValueTypeSizeDep);
  3255. }
  3256. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  3257. {
  3258. if (userType->IsMethodRef())
  3259. {
  3260. // We cannot short-circuit dependencies because of method group ref counting
  3261. }
  3262. else
  3263. return;
  3264. }
  3265. if (usedType->IsSpecializedByAutoCompleteMethod())
  3266. {
  3267. if ((flags & (BfDependencyMap::DependencyFlag_TypeGenericArg | BfDependencyMap::DependencyFlag_MethodGenericArg |
  3268. BfDependencyMap::DependencyFlag_OuterType | BfDependencyMap::DependencyFlag_DerivedFrom)) == 0)
  3269. return;
  3270. }
  3271. // if (usedType->IsBoxed())
  3272. // {
  3273. // NOP;
  3274. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  3275. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  3276. // {
  3277. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  3278. // }
  3279. // }
  3280. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  3281. // BfType* origUsedType = usedType;
  3282. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  3283. // if (isDataAccess)
  3284. // {
  3285. // while (true)
  3286. // {
  3287. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  3288. // usedType = usedType->GetUnderlyingType();
  3289. // else if (usedType->IsArray())
  3290. // {
  3291. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  3292. // }
  3293. // else
  3294. // break;
  3295. // }
  3296. // }
  3297. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  3298. {
  3299. bool addType = true;
  3300. auto checkType = usedType;
  3301. PopulateType(checkType, BfPopulateType_Data);
  3302. if (checkType->IsValuelessType())
  3303. addType = false;
  3304. else if (checkType->IsPrimitiveType())
  3305. addType = false;
  3306. else
  3307. {
  3308. auto checkTypeInst = checkType->ToTypeInstance();
  3309. if (checkTypeInst == NULL)
  3310. {
  3311. addType = false;
  3312. }
  3313. else
  3314. {
  3315. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  3316. addType = false;
  3317. }
  3318. }
  3319. if (addType)
  3320. {
  3321. auto checkTypeInst = checkType->ToTypeInstance();
  3322. if (checkTypeInst->mHotTypeData != NULL)
  3323. {
  3324. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  3325. BF_ASSERT(hotTypeVersion != NULL);
  3326. if (hotTypeVersion != NULL)
  3327. {
  3328. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  3329. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  3330. (checkType->IsComposite()))
  3331. isAllocation = true;
  3332. if (isAllocation)
  3333. {
  3334. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  3335. }
  3336. else
  3337. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  3338. }
  3339. }
  3340. }
  3341. }
  3342. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  3343. {
  3344. auto usingModule = userType->GetModule();
  3345. BfModule* usedModule;
  3346. if (usedType->IsFunction())
  3347. {
  3348. if (mCompiler->mFunctionTypeDef != NULL)
  3349. {
  3350. auto functionType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  3351. usedModule = functionType->GetModule();
  3352. }
  3353. }
  3354. else
  3355. usedModule = usedType->GetModule();
  3356. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  3357. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  3358. {
  3359. if ((flags & ~(BfDependencyMap::DependencyFlag_OuterType)) == 0)
  3360. {
  3361. // Not a 'use' dependency
  3362. }
  3363. else
  3364. {
  3365. usingModule->mModuleRefs.Add(usedModule);
  3366. }
  3367. }
  3368. }
  3369. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  3370. {
  3371. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  3372. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  3373. if (genericArg == usedType)
  3374. return;
  3375. }
  3376. auto depFlag = flags;
  3377. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  3378. {
  3379. if (usedType->IsDependendType())
  3380. {
  3381. // Cause a rebuild but not an outright deletion of the type
  3382. // We can only do this if the 'usedType' can actually hold the dependency which can actually trigger a deletion chain
  3383. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef;
  3384. }
  3385. }
  3386. if (usedType->IsTypeAlias())
  3387. {
  3388. auto underlyingType = usedType->GetUnderlyingType();
  3389. if (underlyingType != NULL)
  3390. {
  3391. BfDepContext newDepContext;
  3392. if (depContext == NULL)
  3393. depContext = &newDepContext;
  3394. if (++depContext->mAliasDepth > 8)
  3395. {
  3396. if (!depContext->mDeepSeenAliases.Add(underlyingType))
  3397. return; // Circular!
  3398. }
  3399. AddDependency(underlyingType, userType, depFlag);
  3400. }
  3401. }
  3402. else if (!usedType->IsGenericTypeInstance())
  3403. {
  3404. auto underlyingType = usedType->GetUnderlyingType();
  3405. if (underlyingType != NULL)
  3406. AddDependency(underlyingType, userType, depFlag);
  3407. }
  3408. BfDependedType* checkDType = usedType->ToDependedType();
  3409. if (checkDType == NULL)
  3410. return;
  3411. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  3412. mContext->MarkAsReferenced(checkDType);
  3413. #ifdef _DEBUG
  3414. // If a MethodRef depends ON US, that means it's a local method that we own
  3415. if (userType->IsMethodRef())
  3416. {
  3417. auto methodRefType = (BfMethodRefType*)userType;
  3418. BF_ASSERT(methodRefType->mOwner == checkDType);
  3419. }
  3420. #endif
  3421. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  3422. return;
  3423. if ((checkDType->IsGenericTypeInstance()) && (!userType->IsMethodRef()))
  3424. {
  3425. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  3426. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3427. {
  3428. AddDependency(genericArg, userType, depFlag);
  3429. }
  3430. }
  3431. if (checkDType->IsTuple())
  3432. {
  3433. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  3434. {
  3435. if (field.mDataIdx != -1)
  3436. AddDependency(field.mResolvedType, userType, depFlag);
  3437. }
  3438. }
  3439. }
  3440. void BfModule::AddDependency(BfGenericParamInstance* genericParam, BfTypeInstance* usingType)
  3441. {
  3442. if ((genericParam->mExternType != NULL) && (!genericParam->mExternType->IsGenericParam()))
  3443. AddDependency(genericParam->mExternType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3444. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  3445. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3446. for (auto& operatorConstraint : genericParam->mOperatorConstraints)
  3447. {
  3448. if (operatorConstraint.mLeftType != NULL)
  3449. AddDependency(operatorConstraint.mLeftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3450. if (operatorConstraint.mRightType != NULL)
  3451. AddDependency(operatorConstraint.mRightType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3452. }
  3453. if (genericParam->mTypeConstraint != NULL)
  3454. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3455. }
  3456. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  3457. {
  3458. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  3459. {
  3460. if (methodInstance->mHotMethod == NULL)
  3461. CheckHotMethod(methodInstance, "");
  3462. BF_ASSERT(methodInstance->mHotMethod != NULL);
  3463. if (devirtualized)
  3464. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  3465. else
  3466. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  3467. }
  3468. }
  3469. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  3470. {
  3471. auto checkTypeInst = typeInst;
  3472. while (checkTypeInst != NULL)
  3473. {
  3474. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  3475. return true;
  3476. checkTypeInst = checkTypeInst->mBaseType;
  3477. }
  3478. return false;
  3479. }
  3480. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  3481. {
  3482. if (mContext->mCurTypeState == NULL)
  3483. return;
  3484. BP_ZONE("PopulateGlobalContainersList");
  3485. BfTypeDef* userTypeDef = GetActiveTypeDef();
  3486. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  3487. {
  3488. mContext->mCurTypeState->mGlobalContainers.Clear();
  3489. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  3490. {
  3491. BfAtomComposite findStr;
  3492. if (namespaceIdx != -1)
  3493. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  3494. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  3495. while (typeDefItr)
  3496. {
  3497. auto typeDef = *typeDefItr;
  3498. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  3499. {
  3500. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  3501. {
  3502. BfGlobalContainerEntry globalEntry;
  3503. globalEntry.mTypeDef = typeDef;
  3504. globalEntry.mTypeInst = NULL;
  3505. typeDef->PopulateMemberSets();
  3506. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  3507. }
  3508. }
  3509. else if (!typeDef->mIsPartial)
  3510. {
  3511. //break;
  3512. }
  3513. typeDefItr.MoveToNextHashMatch();
  3514. }
  3515. }
  3516. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  3517. }
  3518. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  3519. // reifing types
  3520. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  3521. {
  3522. if (globalEntry.mTypeInst == NULL)
  3523. {
  3524. bool include = false;
  3525. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  3526. include = true;
  3527. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  3528. {
  3529. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  3530. include = true;
  3531. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  3532. include = true;
  3533. }
  3534. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  3535. {
  3536. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  3537. include = true;
  3538. }
  3539. if (include)
  3540. {
  3541. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  3542. if (type != NULL)
  3543. globalEntry.mTypeInst = type->ToTypeInstance();
  3544. }
  3545. }
  3546. }
  3547. }
  3548. BfStaticSearch* BfModule::GetStaticSearch()
  3549. {
  3550. auto activeTypeDef = GetActiveTypeDef();
  3551. BfStaticSearch* staticSearch = NULL;
  3552. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3553. return staticSearch;
  3554. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3555. return staticSearch;
  3556. return NULL;
  3557. }
  3558. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  3559. {
  3560. auto activeTypeDef = GetActiveTypeDef();
  3561. BfInternalAccessSet* internalAccessSet = NULL;
  3562. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3563. return internalAccessSet;
  3564. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3565. return internalAccessSet;
  3566. return NULL;
  3567. }
  3568. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  3569. {
  3570. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  3571. return true;
  3572. if ((mCurMethodInstance != NULL) &&
  3573. ((mCurMethodInstance->mIsUnspecializedVariation) || (mCurMethodInstance->IsSpecializedGenericMethod())))
  3574. return true;
  3575. auto internalAccessSet = GetInternalAccessSet();
  3576. if (internalAccessSet == NULL)
  3577. return false;
  3578. for (auto& nameComposite : internalAccessSet->mNamespaces)
  3579. {
  3580. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  3581. return true;
  3582. }
  3583. for (auto internalType : internalAccessSet->mTypes)
  3584. {
  3585. auto checkTypeDef = usingTypeDef->GetDefinition();
  3586. while (checkTypeDef != NULL)
  3587. {
  3588. if (checkTypeDef == internalType->mTypeDef->GetDefinition())
  3589. return true;
  3590. checkTypeDef = checkTypeDef->mOuterType;
  3591. }
  3592. }
  3593. return false;
  3594. }
  3595. void PrintUsers(llvm::MDNode* md);
  3596. BfModuleOptions BfModule::GetModuleOptions()
  3597. {
  3598. if (mIsScratchModule)
  3599. return BfModuleOptions();
  3600. if (mModuleOptions != NULL)
  3601. return *mModuleOptions;
  3602. BfModuleOptions moduleOptions;
  3603. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3604. if (mProject != NULL)
  3605. {
  3606. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3607. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3608. }
  3609. auto headModule = this;
  3610. while (headModule->mParentModule != NULL)
  3611. headModule = headModule->mParentModule;
  3612. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata") || mIsSpecialModule);
  3613. if (headModule->mOwnedTypeInstances.size() > 0)
  3614. {
  3615. auto typeInst = headModule->mOwnedTypeInstances[0];
  3616. if (typeInst->mTypeOptionsIdx == -2)
  3617. PopulateType(typeInst);
  3618. if (typeInst->mTypeOptionsIdx != -1)
  3619. {
  3620. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3621. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3622. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3623. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3624. }
  3625. }
  3626. return moduleOptions;
  3627. }
  3628. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3629. {
  3630. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3631. return BfCheckedKind_Unchecked;
  3632. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3633. auto typeOptions = GetTypeOptions();
  3634. if (typeOptions != NULL)
  3635. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3636. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3637. }
  3638. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3639. {
  3640. BF_ASSERT(typeInstance != NULL);
  3641. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_InFailTypes) != 0)
  3642. return;
  3643. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_InFailTypes);
  3644. mContext->mFailTypes.TryAdd(typeInstance, BfFailKind_Normal);
  3645. }
  3646. void BfModule::DeferRebuildType(BfTypeInstance* typeInstance)
  3647. {
  3648. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_RebuildQueued) != 0)
  3649. return;
  3650. mCompiler->mHasQueuedTypeRebuilds = true;
  3651. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_RebuildQueued);
  3652. AddFailType(typeInstance);
  3653. }
  3654. void BfModule::CheckAddFailType()
  3655. {
  3656. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3657. // but we still need to add the owning type to the FailTypes list
  3658. //.. OLD:
  3659. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3660. /*if (mCurTypeInstance->mModule != this)
  3661. return;*/
  3662. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3663. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3664. // being recompiled. This forces types with warnings to be recompiled.
  3665. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3666. // constantly warning-aware
  3667. if ((mHadBuildError) ||
  3668. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3669. {
  3670. //mContext->mFailTypes.Add(mCurTypeInstance);
  3671. }
  3672. }
  3673. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3674. {
  3675. if (!mCompiler->IsHotCompile())
  3676. return;
  3677. typeInst->mDirty = true;
  3678. for (auto& dep : typeInst->mDependencyMap)
  3679. {
  3680. auto depType = dep.mKey;
  3681. auto depFlags = dep.mValue.mFlags;
  3682. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3683. {
  3684. MarkDerivedDirty(depType->ToTypeInstance());
  3685. }
  3686. }
  3687. }
  3688. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3689. {
  3690. auto fieldType = fieldInstance->GetResolvedType();
  3691. auto field = fieldInstance->GetFieldDef();
  3692. if (fieldType->IsVar())
  3693. return;
  3694. BfIRValue initValue;
  3695. if (field->mIsConst)
  3696. {
  3697. if (fieldType->IsPointer())
  3698. fieldType = fieldType->GetUnderlyingType();
  3699. }
  3700. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3701. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3702. storageKind = BfIRStorageKind_Export;
  3703. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3704. storageKind = BfIRStorageKind_Import;
  3705. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3706. initValue = GetDefaultValue(fieldType);
  3707. if (fieldInstance->mOwner->IsUnspecializedType())
  3708. {
  3709. // Placeholder
  3710. auto ptrVal = CreatePointerType(fieldType);
  3711. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3712. }
  3713. else
  3714. {
  3715. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3716. StringT<4096> staticVarName;
  3717. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3718. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3719. {
  3720. BfIRType irType;
  3721. if ((fieldInstance->IsAppendedObject()) && (!field->mIsStatic))
  3722. {
  3723. irType = mBfIRBuilder->MapTypeInst(fieldType->ToTypeInstance(), BfIRPopulateType_Eventually_Full);
  3724. initValue = mBfIRBuilder->CreateConstAggZero(irType);
  3725. }
  3726. else
  3727. irType = mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full);
  3728. if (fieldType->mSize > 0)
  3729. {
  3730. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3731. irType,
  3732. false,
  3733. BfIRLinkageType_External,
  3734. initValue,
  3735. staticVarName,
  3736. isThreadLocal);
  3737. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3738. if (storageKind != BfIRStorageKind_Normal)
  3739. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3740. BF_ASSERT(globalVar);
  3741. mStaticFieldRefs[fieldInstance] = globalVar;
  3742. }
  3743. }
  3744. }
  3745. }
  3746. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3747. {
  3748. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3749. BfType* fieldType = NULL;
  3750. if (fieldInstance != NULL)
  3751. {
  3752. fieldType = fieldInstance->GetResolvedType();
  3753. if (fieldType == NULL)
  3754. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3755. }
  3756. else
  3757. {
  3758. BF_ASSERT(mCompiler->IsAutocomplete());
  3759. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3760. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3761. {
  3762. fieldType = typeInstance;
  3763. }
  3764. else
  3765. {
  3766. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3767. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3768. if (isLet || isVar)
  3769. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3770. else
  3771. fieldType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  3772. if (fieldType == NULL)
  3773. fieldType = mContext->mBfObjectType;
  3774. }
  3775. }
  3776. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3777. return;
  3778. if (mContext->mFieldResolveReentrys.size() > 1)
  3779. {
  3780. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3781. {
  3782. String failStr = "Circular data reference detected between the following fields:";
  3783. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3784. {
  3785. if (i > 1)
  3786. failStr += ",";
  3787. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3788. }
  3789. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3790. if (err)
  3791. err->mIsPersistent = true;
  3792. return;
  3793. }
  3794. }
  3795. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3796. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3797. if (fieldInstance == NULL)
  3798. popTypeResolveReentry.Pop();
  3799. auto typeDef = typeInstance->mTypeDef;
  3800. BfIRValue constValue;
  3801. if (fieldDef->mIsExtern)
  3802. {
  3803. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3804. {
  3805. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3806. Fail("Extern consts must be pointer types", fieldDef->mTypeRef);
  3807. }
  3808. if (fieldDef->GetInitializer() != NULL)
  3809. {
  3810. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3811. Fail("Extern consts cannot have initializers", fieldDef->GetNameNode());
  3812. }
  3813. }
  3814. else if (fieldDef->GetInitializer() == NULL)
  3815. {
  3816. if (fieldDef->IsEnumCaseEntry())
  3817. {
  3818. if (typeInstance->IsTypedPrimitive())
  3819. {
  3820. BfFieldInstance* prevFieldInstance = NULL;
  3821. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3822. {
  3823. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3824. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3825. {
  3826. prevFieldInstance = checkFieldInst;
  3827. break;
  3828. }
  3829. }
  3830. if (prevFieldInstance == NULL)
  3831. constValue = GetConstValue(0, typeInstance);
  3832. else
  3833. {
  3834. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3835. if (prevFieldInstance->mConstIdx == -1)
  3836. {
  3837. if (!mCompiler->IsAutocomplete())
  3838. AssertErrorState();
  3839. constValue = GetConstValue(0, typeInstance);
  3840. }
  3841. else
  3842. {
  3843. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3844. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3845. }
  3846. }
  3847. }
  3848. }
  3849. else
  3850. {
  3851. Fail("Const requires initializer", fieldDef->GetNameNode());
  3852. }
  3853. }
  3854. else if (mBfIRBuilder != NULL)
  3855. {
  3856. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3857. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3858. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3859. BfMethodState methodState;
  3860. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3861. methodState.mTempKind = BfMethodState::TempKind_Static;
  3862. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3863. if ((fieldType->IsVar()) || (fieldType->IsUndefSizedArray()))
  3864. {
  3865. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3866. if (!initValue)
  3867. {
  3868. AssertErrorState();
  3869. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3870. }
  3871. if (fieldInstance != NULL)
  3872. {
  3873. if (fieldType->IsUndefSizedArray())
  3874. {
  3875. if ((initValue.mType->IsSizedArray()) && (initValue.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3876. {
  3877. fieldInstance->mResolvedType = initValue.mType;
  3878. }
  3879. }
  3880. else
  3881. fieldInstance->mResolvedType = initValue.mType;
  3882. }
  3883. constValue = initValue.mValue;
  3884. }
  3885. else
  3886. {
  3887. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3888. constValue = uncastedInitValue.mValue;
  3889. }
  3890. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3891. {
  3892. // Illegal
  3893. constValue = BfIRValue();
  3894. }
  3895. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3896. }
  3897. if (fieldInstance != NULL)
  3898. {
  3899. fieldType = fieldInstance->GetResolvedType();
  3900. if ((fieldType == NULL) || (fieldType->IsVar()))
  3901. {
  3902. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3903. AssertErrorState();
  3904. // Default const type is 'int'
  3905. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3906. if (fieldInstance != NULL)
  3907. {
  3908. fieldInstance->mResolvedType = initValue.mType;
  3909. }
  3910. constValue = initValue.mValue;
  3911. }
  3912. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3913. {
  3914. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3915. CurrentAddToConstHolder(constValue);
  3916. fieldInstance->mConstIdx = constValue.mId;
  3917. }
  3918. }
  3919. }
  3920. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3921. {
  3922. bool isDeclType = (field->mFieldDeclaration != NULL) && BfNodeDynCastExact<BfExprModTypeRef>(field->mTypeRef) != NULL;
  3923. auto fieldType = fieldInstance->GetResolvedType();
  3924. if ((field->mIsConst) && (!isDeclType))
  3925. {
  3926. ResolveConstField(typeInstance, fieldInstance, field);
  3927. return fieldInstance->GetResolvedType();
  3928. }
  3929. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3930. if (!fieldInstance->mIsInferredType)
  3931. return fieldType;
  3932. if ((!fieldType->IsVar()) && (!fieldType->IsUndefSizedArray()))
  3933. return fieldType;
  3934. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3935. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3936. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mType != typeInstance);
  3937. auto typeDef = typeInstance->mTypeDef;
  3938. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3939. {
  3940. AssertErrorState();
  3941. return fieldType;
  3942. }
  3943. bool hadInferenceCycle = false;
  3944. if (mContext->mFieldResolveReentrys.size() > 1)
  3945. {
  3946. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3947. {
  3948. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3949. {
  3950. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3951. auto fieldDef = fieldInst->GetFieldDef();
  3952. auto fieldOwner = fieldInst->mOwner;
  3953. auto fieldModule = fieldOwner->mModule;
  3954. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3955. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3956. }
  3957. return fieldType;
  3958. }
  3959. }
  3960. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3961. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3962. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3963. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3964. if ((field->GetInitializer() == NULL) && (!isDeclType))
  3965. {
  3966. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3967. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3968. return fieldType;
  3969. }
  3970. BfType* resolvedType = NULL;
  3971. if (!hadInferenceCycle)
  3972. {
  3973. BfTypeState typeState;
  3974. typeState.mPrevState = mContext->mCurTypeState;
  3975. typeState.mType = typeInstance;
  3976. typeState.mCurFieldDef = field;
  3977. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3978. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3979. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3980. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3981. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3982. BfMethodState methodState;
  3983. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3984. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3985. if (!staticOnly)
  3986. {
  3987. //BfLocalVariable localVar;
  3988. //methodState.mLocals.push_back(localVar);
  3989. }
  3990. if (isDeclType)
  3991. {
  3992. auto fieldDef = fieldInstance->GetFieldDef();
  3993. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3994. }
  3995. else
  3996. {
  3997. BfTypedValue valueFromExpr;
  3998. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3999. FixIntUnknown(valueFromExpr);
  4000. if (fieldType->IsUndefSizedArray())
  4001. {
  4002. if ((valueFromExpr.mType != NULL) && (valueFromExpr.mType->IsSizedArray()) && (valueFromExpr.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  4003. resolvedType = valueFromExpr.mType;
  4004. }
  4005. else
  4006. resolvedType = valueFromExpr.mType;
  4007. }
  4008. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  4009. }
  4010. if (resolvedType == NULL)
  4011. return fieldType;
  4012. fieldInstance->SetResolvedType(resolvedType);
  4013. if (field->mIsStatic)
  4014. {
  4015. }
  4016. else if (fieldInstance->mDataIdx >= 0)
  4017. {
  4018. }
  4019. else
  4020. {
  4021. BF_ASSERT(typeInstance->IsIncomplete());
  4022. }
  4023. return resolvedType;
  4024. }
  4025. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  4026. {
  4027. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  4028. auto fieldType = fieldInstance->GetResolvedType();
  4029. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  4030. {
  4031. int fieldIdx = 0;
  4032. int fieldCount = 0;
  4033. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  4034. fieldIdx--;
  4035. int count = fieldCount;
  4036. if (fieldIdx == -1)
  4037. count = 1;
  4038. //TODO: Under what circumstances could 'thisVariable' be NULL?
  4039. auto thisVariable = GetThisVariable();
  4040. if (thisVariable != NULL)
  4041. {
  4042. for (int i = 0; i < count; i++)
  4043. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  4044. }
  4045. }
  4046. }
  4047. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  4048. {
  4049. if (fieldInstance->mCustomAttributes == NULL)
  4050. return false;
  4051. auto fieldDef = fieldInstance->GetFieldDef();
  4052. if (!fieldDef->mIsStatic)
  4053. return false;
  4054. bool isThreadLocal = false;
  4055. if (fieldInstance->mCustomAttributes != NULL)
  4056. {
  4057. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4058. {
  4059. if (customAttr.mType->ToTypeInstance()->IsInstanceOf(mCompiler->mThreadStaticAttributeTypeDef))
  4060. return true;
  4061. }
  4062. }
  4063. return false;
  4064. }
  4065. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  4066. {
  4067. if (fieldDef == NULL)
  4068. fieldDef = fieldInstance->GetFieldDef();
  4069. if (fieldType == NULL)
  4070. fieldType = fieldInstance->GetResolvedType();
  4071. if (initializer == NULL)
  4072. {
  4073. if (fieldDef == NULL)
  4074. return BfTypedValue();
  4075. initializer = fieldDef->GetInitializer();
  4076. }
  4077. BfTypedValue staticVarRef;
  4078. BfTypedValue result;
  4079. if (initializer == NULL)
  4080. {
  4081. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  4082. }
  4083. else
  4084. {
  4085. if (mCompiler->mIsResolveOnly)
  4086. {
  4087. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  4088. {
  4089. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  4090. sourceClassifier->VisitChildNoRef(initializer);
  4091. }
  4092. }
  4093. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  4094. {
  4095. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  4096. BfConstResolver constResolver(this);
  4097. constResolver.Resolve(initializer);
  4098. return GetDefaultTypedValue(fieldType);
  4099. }
  4100. else if (mCurTypeInstance->IsUnspecializedTypeVariation())
  4101. {
  4102. return GetDefaultTypedValue(fieldType);
  4103. }
  4104. else if (fieldDef->mIsConst)
  4105. {
  4106. int ceExecuteId = -1;
  4107. if (mCompiler->mCeMachine != NULL)
  4108. ceExecuteId = mCompiler->mCeMachine->mExecuteId;
  4109. BfTypeState typeState;
  4110. typeState.mType = mCurTypeInstance;
  4111. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  4112. typeState.mCurFieldDef = fieldDef;
  4113. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  4114. BfConstResolver constResolver(this);
  4115. if (fieldType->IsVar())
  4116. return constResolver.Resolve(initializer);
  4117. else
  4118. {
  4119. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  4120. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  4121. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  4122. {
  4123. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  4124. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  4125. resolveFlags = BfConstResolveFlag_NoCast;
  4126. }
  4127. if ((mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()))
  4128. resolveFlags = (BfConstResolveFlags)(resolveFlags | BfConstResolveFlag_NoConversionOperator | BfConstResolveFlag_ExplicitCast);
  4129. UpdateSrcPos(initializer);
  4130. auto result = constResolver.Resolve(initializer, fieldType, resolveFlags);
  4131. if ((mCompiler->mCeMachine != NULL) && (fieldInstance != NULL))
  4132. {
  4133. if (mCompiler->mCeMachine->mExecuteId != ceExecuteId)
  4134. fieldInstance->mHadConstEval = true;
  4135. }
  4136. if (auto autoComplete = mCompiler->GetAutoComplete())
  4137. autoComplete->CheckResult(initializer, result);
  4138. return result;
  4139. }
  4140. }
  4141. BfExprEvaluator exprEvaluator(this);
  4142. if (doStore)
  4143. {
  4144. staticVarRef = ReferenceStaticField(fieldInstance);
  4145. exprEvaluator.mReceivingValue = &staticVarRef;
  4146. }
  4147. if (fieldType->IsDeleting())
  4148. {
  4149. mCompiler->RequestExtraCompile();
  4150. InternalError("Field using deleted type", fieldDef->GetRefNode());
  4151. }
  4152. else if (fieldType->IsVar())
  4153. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4154. else
  4155. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4156. if (doStore)
  4157. {
  4158. if (exprEvaluator.mReceivingValue == NULL)
  4159. doStore = false; // Already stored
  4160. }
  4161. }
  4162. if (fieldInstance != NULL)
  4163. MarkFieldInitialized(fieldInstance);
  4164. if ((doStore) && (result))
  4165. {
  4166. if (fieldInstance->mResolvedType->IsUndefSizedArray())
  4167. {
  4168. if ((!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mFastFinish))
  4169. AssertErrorState();
  4170. }
  4171. else
  4172. {
  4173. result = LoadValue(result);
  4174. if (!result.mType->IsValuelessType())
  4175. mBfIRBuilder->CreateAlignedStore(result.mValue, staticVarRef.mValue, result.mType->mAlign);
  4176. }
  4177. }
  4178. return result;
  4179. }
  4180. bool BfModule::TryGetAppendedObjectInfo(BfFieldInstance* fieldInstance, int& dataSize, int& alignSize)
  4181. {
  4182. auto resolvedFieldType = fieldInstance->GetResolvedType();
  4183. auto fieldDef = fieldInstance->GetFieldDef();
  4184. BfAstNode* nameRefNode = NULL;
  4185. if (auto fieldDecl = fieldDef->GetFieldDeclaration())
  4186. nameRefNode = fieldDecl->mNameNode;
  4187. else if (auto paramDecl = fieldDef->GetParamDeclaration())
  4188. nameRefNode = paramDecl->mNameNode;
  4189. if (nameRefNode == NULL)
  4190. nameRefNode = fieldDef->mTypeRef;
  4191. dataSize = resolvedFieldType->mSize;
  4192. alignSize = resolvedFieldType->mAlign;
  4193. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, fieldDef);
  4194. SetAndRestoreValue<BfTypeState::ResolveKind> prevResolveKind(mContext->mCurTypeState->mResolveKind, BfTypeState::ResolveKind_FieldType);
  4195. PopulateType(resolvedFieldType, BfPopulateType_Data);
  4196. auto fieldTypeInst = resolvedFieldType->ToTypeInstance();
  4197. dataSize = BF_MAX(fieldTypeInst->mInstSize, 0);
  4198. alignSize = BF_MAX(fieldTypeInst->mInstAlign, 1);
  4199. if (fieldTypeInst->mTypeFailed)
  4200. {
  4201. TypeFailed(fieldTypeInst);
  4202. fieldInstance->mResolvedType = GetPrimitiveType(BfTypeCode_Var);
  4203. return false;
  4204. }
  4205. if ((fieldTypeInst != NULL) && (fieldTypeInst->mTypeDef->mIsAbstract))
  4206. {
  4207. Fail("Cannot create an instance of an abstract class", nameRefNode);
  4208. }
  4209. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  4210. BfMethodState methodState;
  4211. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4212. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  4213. BfTypedValue appendIndexValue;
  4214. BfExprEvaluator exprEvaluator(this);
  4215. BfResolvedArgs resolvedArgs;
  4216. auto fieldDecl = fieldDef->GetFieldDeclaration();
  4217. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(fieldDecl->mInitializer))
  4218. {
  4219. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  4220. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  4221. }
  4222. BfFunctionBindResult bindResult;
  4223. bindResult.mSkipThis = true;
  4224. bindResult.mWantsArgs = true;
  4225. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  4226. BfTypedValue emptyThis(mBfIRBuilder->GetFakeVal(), mCurTypeInstance, mCurTypeInstance->IsStruct());
  4227. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_Comptime;
  4228. auto ctorResult = exprEvaluator.MatchConstructor(nameRefNode, NULL, emptyThis, fieldTypeInst, resolvedArgs, false, BfMethodGenericArguments(), BfAllowAppendKind_Infer);
  4229. if ((bindResult.mMethodInstance != NULL) && (bindResult.mMethodInstance->mMethodDef->HasAppend()))
  4230. {
  4231. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  4232. SizedArray<BfIRValue, 2> irArgs;
  4233. if (bindResult.mIRArgs.size() > 1)
  4234. irArgs.Insert(0, &bindResult.mIRArgs[1], bindResult.mIRArgs.size() - 1);
  4235. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, irArgs, true);
  4236. if (appendSizeTypedValue)
  4237. {
  4238. int appendAlign = calcAppendMethodModule.mMethodInstance->mAppendAllocAlign;
  4239. dataSize = BF_ALIGN(dataSize, appendAlign);
  4240. alignSize = BF_MAX(alignSize, appendAlign);
  4241. auto constant = mBfIRBuilder->GetConstant(appendSizeTypedValue.mValue);
  4242. if (constant != NULL)
  4243. {
  4244. dataSize += constant->mInt32;
  4245. }
  4246. }
  4247. else
  4248. {
  4249. Fail(StrFormat("Append constructor '%s' does not result in a constant size", MethodToString(bindResult.mMethodInstance).c_str()), nameRefNode);
  4250. }
  4251. }
  4252. return true;
  4253. }
  4254. void BfModule::AppendedObjectInit(BfFieldInstance* fieldInst)
  4255. {
  4256. BfExprEvaluator exprEvaluator(this);
  4257. bool failed = false;
  4258. auto fieldDef = fieldInst->GetFieldDef();
  4259. auto initializer = fieldDef->GetInitializer();
  4260. BfResolvedArgs resolvedArgs;
  4261. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(initializer))
  4262. {
  4263. bool isDot = false;
  4264. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  4265. isDot = (memberRefExpr->mTarget == NULL) && (memberRefExpr->mMemberName == NULL);
  4266. if (!isDot)
  4267. {
  4268. auto resolvedType = ResolveTypeRef(invocationExpr->mTarget, {});
  4269. if ((resolvedType == NULL) || (resolvedType != fieldInst->mResolvedType))
  4270. failed = true;
  4271. }
  4272. SetAndRestoreValue<BfType*> prevExpectingType(exprEvaluator.mExpectingType, fieldInst->mResolvedType);
  4273. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  4274. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  4275. }
  4276. else if (initializer != NULL)
  4277. {
  4278. GetFieldInitializerValue(fieldInst);
  4279. failed = true;
  4280. }
  4281. if (failed)
  4282. Fail("Append fields can only be initialized with a call to their constructor", initializer);
  4283. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  4284. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4285. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4286. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  4287. auto fieldTypeInst = fieldInst->mResolvedType->ToTypeInstance();
  4288. BfIRValue fieldAddr;
  4289. if (fieldDef->mIsStatic)
  4290. {
  4291. auto fieldTypedValue = ReferenceStaticField(fieldInst);
  4292. int dataSize = 1;
  4293. int alignSize = 1;
  4294. TryGetAppendedObjectInfo(fieldInst, dataSize, alignSize);
  4295. String dataName;
  4296. BfMangler::MangleStaticFieldName(dataName, mCompiler->GetMangleKind(), mCurTypeInstance, fieldDef->mName, fieldInst->mResolvedType);
  4297. dataName += "__DATA";
  4298. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8), dataSize);
  4299. auto globalVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8), dataSize), false,
  4300. BfIRLinkageType_Internal, mBfIRBuilder->CreateConstArrayZero(dataSize), dataName);
  4301. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, alignSize);
  4302. auto castedVal = mBfIRBuilder->CreateBitCast(globalVar, mBfIRBuilder->MapType(fieldInst->mResolvedType));
  4303. mBfIRBuilder->CreateStore(castedVal, fieldTypedValue.mValue);
  4304. fieldTypedValue = LoadValue(fieldTypedValue);
  4305. fieldAddr = fieldTypedValue.mValue;
  4306. }
  4307. else
  4308. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  4309. auto thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  4310. auto indexVal = BfTypedValue(CreateAlloca(intType), CreateRefType(intType));
  4311. auto intThisVal = mBfIRBuilder->CreatePtrToInt(thisValue.mValue, (intType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  4312. auto curValPtr = mBfIRBuilder->CreateAdd(intThisVal, GetConstValue(fieldTypeInst->mInstSize, intType));
  4313. mBfIRBuilder->CreateStore(curValPtr, indexVal.mValue);
  4314. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 0);
  4315. auto vDataRef = CreateClassVDataGlobal(fieldInst->mResolvedType->ToTypeInstance());
  4316. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  4317. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  4318. mBfIRBuilder->CreateStore(srcVal, destAddr);
  4319. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  4320. {
  4321. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4322. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4323. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(thisValue.mValue, ptrType);
  4324. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_AppendAlloc), thisFlagsPtr);
  4325. }
  4326. exprEvaluator.MatchConstructor(fieldDef->GetNameNode(), NULL, thisValue, fieldInst->mResolvedType->ToTypeInstance(), resolvedArgs, false, BfMethodGenericArguments(), BfAllowAppendKind_Infer, &indexVal);
  4327. }
  4328. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  4329. {
  4330. }
  4331. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  4332. {
  4333. PopulateType(classType);
  4334. if (isInterfacePass)
  4335. {
  4336. for (auto ifaceInst : classType->mInterfaces)
  4337. {
  4338. if (exChecks->Contains(ifaceInst.mInterfaceType))
  4339. continue;
  4340. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  4341. continue;
  4342. if (ifaceInst.mDeclaringType->IsExtension())
  4343. {
  4344. bool needsExCheck = false;
  4345. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  4346. {
  4347. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  4348. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  4349. {
  4350. exChecks->push_back(ifaceInst.mInterfaceType);
  4351. continue;
  4352. }
  4353. else
  4354. {
  4355. // We can only do an 'exCheck' if we're actually going to slot this interface
  4356. }
  4357. }
  4358. }
  4359. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  4360. }
  4361. }
  4362. else
  4363. {
  4364. outVals->push_back(classType->mTypeId);
  4365. }
  4366. if (classType->mBaseType != NULL)
  4367. {
  4368. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  4369. }
  4370. }
  4371. void BfModule::CreateDynamicCastMethod()
  4372. {
  4373. auto objType = mContext->mBfObjectType;
  4374. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  4375. {
  4376. // The main reason to punt on this method for ResolveOnly is because types can be created
  4377. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  4378. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  4379. // remove this punt when we recycle typeId's
  4380. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  4381. mCurMethodState->mHadReturn = true;
  4382. return;
  4383. }
  4384. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  4385. bool isSignaturePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_SIGNATURE;
  4386. auto func = mCurMethodState->mIRFunction;
  4387. auto thisValue = mBfIRBuilder->GetArgument(0);
  4388. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  4389. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  4390. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  4391. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  4392. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4393. Array<BfIRValue> incomingFalses;
  4394. BfIRBlock curBlock;
  4395. if (isSignaturePass)
  4396. {
  4397. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  4398. curBlock = mBfIRBuilder->GetInsertBlock();
  4399. auto signatureId = GetDelegateSignatureId(mCurTypeInstance);
  4400. auto eqResult = mBfIRBuilder->CreateCmpEQ(typeIdValue, GetConstValue32(signatureId));
  4401. mBfIRBuilder->CreateCondBr(eqResult, trueBB, exitBB);
  4402. }
  4403. else
  4404. {
  4405. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4406. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  4407. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  4408. SizedArray<int, 8> typeMatches;
  4409. SizedArray<BfTypeInstance*, 8> exChecks;
  4410. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  4411. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  4412. {
  4413. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  4414. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  4415. BfTypeVector genericArgs;
  4416. for (int i = 0; i < (int)genericTypeInst->mGenericParamDefs.size(); i++)
  4417. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  4418. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef->GetDefinition(), genericArgs, BfPopulateType_Declaration);
  4419. typeMatches.push_back(unboundType->mTypeId);
  4420. }
  4421. if (mCurTypeInstance->IsBoxed())
  4422. {
  4423. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  4424. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  4425. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  4426. if (innerType->IsTypedPrimitive())
  4427. {
  4428. auto underlyingType = innerType->GetUnderlyingType();
  4429. typeMatches.push_back(underlyingType->mTypeId);
  4430. }
  4431. auto innerTypeInst = innerType->ToTypeInstance();
  4432. if ((innerTypeInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef)) ||
  4433. (innerTypeInst->IsInstanceOf(mCompiler->mPointerTTypeDef)) ||
  4434. (innerTypeInst->IsInstanceOf(mCompiler->mMethodRefTypeDef)))
  4435. {
  4436. PopulateType(innerTypeInst);
  4437. //TODO: What case was this supposed to handle?
  4438. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  4439. }
  4440. }
  4441. curBlock = mBfIRBuilder->GetInsertBlock();
  4442. BfIRValue vDataPtr;
  4443. if (!exChecks.empty())
  4444. {
  4445. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4446. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  4447. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  4448. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4449. }
  4450. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  4451. for (auto typeMatch : typeMatches)
  4452. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  4453. for (auto ifaceTypeInst : exChecks)
  4454. {
  4455. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  4456. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  4457. mBfIRBuilder->SetInsertPoint(nextBB);
  4458. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  4459. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4460. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4461. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4462. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  4463. incomingFalses.push_back(nextBB);
  4464. }
  4465. }
  4466. mBfIRBuilder->AddBlock(trueBB);
  4467. mBfIRBuilder->SetInsertPoint(trueBB);
  4468. mBfIRBuilder->CreateBr(exitBB);
  4469. mBfIRBuilder->AddBlock(exitBB);
  4470. mBfIRBuilder->SetInsertPoint(exitBB);
  4471. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  4472. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  4473. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  4474. for (auto incomingFalseBlock : incomingFalses)
  4475. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  4476. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  4477. mBfIRBuilder->CreateRet(phi);
  4478. mCurMethodState->mHadReturn = true;
  4479. }
  4480. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  4481. {
  4482. BfExprEvaluator exprEvaluator(this);
  4483. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  4484. auto typeInst = rightValue.mType->ToTypeInstance();
  4485. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  4486. BfTypedValue result = exprEvaluator.GetResult();
  4487. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  4488. {
  4489. // Fail?
  4490. }
  4491. if ((result) && (!result.mType->IsVar()))
  4492. {
  4493. auto nextBB = mBfIRBuilder->CreateBlock("next");
  4494. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  4495. mBfIRBuilder->AddBlock(nextBB);
  4496. mBfIRBuilder->SetInsertPoint(nextBB);
  4497. }
  4498. }
  4499. void BfModule::CreateFakeCallerMethod(const String& funcName)
  4500. {
  4501. if (mCurMethodInstance->mHasFailed)
  4502. return;
  4503. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  4504. return;
  4505. BF_ASSERT(mCurMethodInstance->mIRFunction);
  4506. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  4507. SizedArray<BfIRType, 4> paramTypes;
  4508. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  4509. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  4510. mBfIRBuilder->SetActiveFunction(func);
  4511. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  4512. mBfIRBuilder->SetInsertPoint(entryBlock);
  4513. BfMethodState methodState;
  4514. methodState.mIRHeadBlock = entryBlock;
  4515. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4516. SizedArray<BfIRValue, 8> args;
  4517. BfExprEvaluator exprEvaluator(this);
  4518. if (mCurMethodInstance->GetStructRetIdx() == 0)
  4519. {
  4520. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4521. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4522. }
  4523. if (mCurMethodInstance->HasThis())
  4524. {
  4525. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  4526. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  4527. }
  4528. if (mCurMethodInstance->GetStructRetIdx() == 1)
  4529. {
  4530. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4531. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4532. }
  4533. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  4534. {
  4535. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  4536. if (paramType->IsValuelessType())
  4537. continue;
  4538. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  4539. }
  4540. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  4541. mBfIRBuilder->CreateRetVoid();
  4542. }
  4543. void BfModule::CreateDelegateEqualsMethod()
  4544. {
  4545. if (mBfIRBuilder->mIgnoreWrites)
  4546. return;
  4547. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4548. if (refNode == NULL)
  4549. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4550. UpdateSrcPos(refNode);
  4551. SetIllegalSrcPos();
  4552. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4553. auto resultVal = CreateAlloca(boolType);
  4554. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4555. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4556. auto delegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  4557. mBfIRBuilder->PopulateType(delegateType);
  4558. BfExprEvaluator exprEvaluator(this);
  4559. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4560. BfTypedValue lhsDelegate = BfTypedValue(mBfIRBuilder->CreateBitCast(leftTypedVal.mValue, mBfIRBuilder->MapType(delegateType)), delegateType);
  4561. BfTypedValue rhsDelegate = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4562. rhsDelegate = LoadValue(rhsDelegate);
  4563. BfTypedValue rightTypedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(rhsDelegate.mValue, mBfIRBuilder->MapType(mCurTypeInstance)), mCurTypeInstance);
  4564. auto& targetFieldInstance = delegateType->mFieldInstances[0];
  4565. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(lhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4566. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4567. leftValue = LoadValue(leftValue);
  4568. rightValue = LoadValue(rightValue);
  4569. EmitEquals(leftValue, rightValue, exitBB, false);
  4570. bool hadComparison = false;
  4571. for (auto& fieldRef : mCurTypeInstance->mFieldInstances)
  4572. {
  4573. BfFieldInstance* fieldInstance = &fieldRef;
  4574. if (fieldInstance->mDataOffset == -1)
  4575. continue;
  4576. auto fieldType = fieldInstance->mResolvedType;
  4577. if (fieldType->IsValuelessType())
  4578. continue;
  4579. if (fieldType->IsVar())
  4580. continue;
  4581. if (fieldType->IsMethodRef())
  4582. continue;
  4583. if (fieldType->IsRef())
  4584. fieldType = CreatePointerType(fieldType->GetUnderlyingType());
  4585. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(leftTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4586. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rightTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4587. if (!fieldInstance->mResolvedType->IsComposite())
  4588. {
  4589. leftValue = LoadValue(leftValue);
  4590. rightValue = LoadValue(rightValue);
  4591. }
  4592. EmitEquals(leftValue, rightValue, exitBB, false);
  4593. }
  4594. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4595. mBfIRBuilder->CreateBr(exitBB);
  4596. mBfIRBuilder->AddBlock(exitBB);
  4597. mBfIRBuilder->SetInsertPoint(exitBB);
  4598. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4599. ClearLifetimeEnds();
  4600. mBfIRBuilder->CreateRet(loadedResult);
  4601. mCurMethodState->mHadReturn = true;
  4602. }
  4603. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  4604. {
  4605. if (mCurMethodInstance->mIsUnspecialized)
  4606. return;
  4607. if (mBfIRBuilder->mIgnoreWrites)
  4608. return;
  4609. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  4610. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  4611. bool isValid = true;
  4612. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4613. if (compareType->IsValuelessType())
  4614. {
  4615. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4616. return;
  4617. }
  4618. if (compareType->IsTypedPrimitive())
  4619. {
  4620. BfExprEvaluator exprEvaluator(this);
  4621. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  4622. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  4623. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  4624. mBfIRBuilder->CreateRet(cmpResult);
  4625. return;
  4626. }
  4627. auto compareDType = compareType->ToDependedType();
  4628. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  4629. if (compareTypeInst != NULL)
  4630. {
  4631. if (compareType->IsPrimitiveType())
  4632. compareTypeInst = GetWrappedStructType(compareType);
  4633. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  4634. {
  4635. isValid = false;
  4636. }
  4637. mBfIRBuilder->PopulateType(compareTypeInst);
  4638. }
  4639. if (!isValid)
  4640. {
  4641. ClearLifetimeEnds();
  4642. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4643. return;
  4644. }
  4645. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  4646. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4647. if (refNode == NULL)
  4648. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4649. UpdateSrcPos(refNode);
  4650. SetIllegalSrcPos();
  4651. auto resultVal = CreateAlloca(boolType);
  4652. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4653. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4654. if (compareType->IsValuelessType())
  4655. {
  4656. // Always equal, nothing to do
  4657. }
  4658. else if (compareType->IsSizedArray())
  4659. {
  4660. auto sizedArrayType = (BfSizedArrayType*)compareType;
  4661. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  4662. {
  4663. BfTypedValue result;
  4664. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index, true);
  4665. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4666. if (!result.mType->IsValueType())
  4667. result = LoadValue(result);
  4668. return result;
  4669. };
  4670. if (sizedArrayType->mElementCount > 6)
  4671. {
  4672. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4673. auto itr = CreateAlloca(intPtrType);
  4674. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  4675. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  4676. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  4677. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  4678. mBfIRBuilder->CreateBr(loopBB);
  4679. mBfIRBuilder->SetInsertPoint(loopBB);
  4680. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  4681. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  4682. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  4683. mBfIRBuilder->SetInsertPoint(bodyBB);
  4684. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  4685. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  4686. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4687. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  4688. mBfIRBuilder->CreateStore(incValue, itr);
  4689. mBfIRBuilder->CreateBr(loopBB);
  4690. mBfIRBuilder->SetInsertPoint(doneBB);
  4691. }
  4692. else
  4693. {
  4694. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  4695. {
  4696. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4697. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4698. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4699. }
  4700. }
  4701. }
  4702. else if (compareType->IsMethodRef())
  4703. {
  4704. auto methodRefType = (BfMethodRefType*)compareType;
  4705. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  4706. BfExprEvaluator exprEvaluator(this);
  4707. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4708. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4709. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  4710. // values for the same method reference -- they will always refer back to the same local variables.
  4711. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  4712. if (dataIdx != -1)
  4713. {
  4714. bool failed = false;
  4715. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  4716. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  4717. BF_ASSERT(!failed);
  4718. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4719. }
  4720. }
  4721. else if (compareTypeInst->IsEnum())
  4722. {
  4723. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4724. BfExprEvaluator exprEvaluator(this);
  4725. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4726. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4727. auto dscrType = compareTypeInst->GetDiscriminatorType();
  4728. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  4729. leftValue = LoadValue(leftValue);
  4730. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  4731. rightValue = LoadValue(rightValue);
  4732. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  4733. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  4734. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4735. int enumCount = 0;
  4736. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4737. {
  4738. BfFieldInstance* fieldInstance = &fieldRef;
  4739. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4740. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4741. {
  4742. enumCount = -fieldInstance->mDataIdx;
  4743. }
  4744. }
  4745. if (enumCount > 0)
  4746. {
  4747. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  4748. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  4749. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4750. {
  4751. BfFieldInstance* fieldInstance = &fieldRef;
  4752. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4753. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4754. {
  4755. int enumIdx = -fieldInstance->mDataIdx - 1;
  4756. if (fieldInstance->mResolvedType->mSize == 0)
  4757. {
  4758. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  4759. }
  4760. else
  4761. {
  4762. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  4763. mBfIRBuilder->SetInsertPoint(caseBlock);
  4764. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  4765. BfTypedValue leftTuple;
  4766. BfTypedValue rightTuple;
  4767. if (leftPayload.IsAddr())
  4768. {
  4769. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4770. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4771. }
  4772. else
  4773. {
  4774. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4775. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4776. }
  4777. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  4778. mBfIRBuilder->CreateBr(matchedBlock);
  4779. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  4780. }
  4781. }
  4782. }
  4783. mBfIRBuilder->AddBlock(matchedBlock);
  4784. mBfIRBuilder->SetInsertPoint(matchedBlock);
  4785. }
  4786. }
  4787. else if (compareTypeInst->IsUnion())
  4788. {
  4789. auto innerType = compareTypeInst->GetUnionInnerType();
  4790. if (!innerType->IsValuelessType())
  4791. {
  4792. BfExprEvaluator exprEvaluator(this);
  4793. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4794. leftTypedVal = AggregateSplat(leftTypedVal);
  4795. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  4796. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4797. rightTypedVal = AggregateSplat(rightTypedVal);
  4798. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  4799. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  4800. }
  4801. }
  4802. else
  4803. {
  4804. BfExprEvaluator exprEvaluator(this);
  4805. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4806. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4807. bool hadComparison = false;
  4808. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4809. {
  4810. BfFieldInstance* fieldInstance = &fieldRef;
  4811. if (fieldInstance->mDataOffset == -1)
  4812. continue;
  4813. if (fieldInstance->mResolvedType->IsValuelessType())
  4814. continue;
  4815. if (fieldInstance->mResolvedType->IsVar())
  4816. continue;
  4817. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4818. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4819. if (!fieldInstance->mResolvedType->IsComposite())
  4820. {
  4821. leftValue = LoadValue(leftValue);
  4822. rightValue = LoadValue(rightValue);
  4823. }
  4824. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4825. }
  4826. auto baseTypeInst = compareTypeInst->mBaseType;
  4827. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  4828. {
  4829. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  4830. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  4831. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4832. }
  4833. }
  4834. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4835. mBfIRBuilder->CreateBr(exitBB);
  4836. mBfIRBuilder->AddBlock(exitBB);
  4837. mBfIRBuilder->SetInsertPoint(exitBB);
  4838. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4839. ClearLifetimeEnds();
  4840. mBfIRBuilder->CreateRet(loadedResult);
  4841. mCurMethodState->mHadReturn = true;
  4842. }
  4843. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  4844. {
  4845. if (mBfIRBuilder->mIgnoreWrites)
  4846. return mBfIRBuilder->GetFakeVal();
  4847. PopulateType(typeInstance, mIsComptimeModule ? BfPopulateType_Data : BfPopulateType_DataAndMethods);
  4848. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4849. if (mIsComptimeModule)
  4850. {
  4851. auto idVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, typeInstance->mTypeId);
  4852. return mBfIRBuilder->CreateIntToPtr(idVal, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4853. }
  4854. BfIRValue* globalVariablePtr = NULL;
  4855. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  4856. int numElements = 1;
  4857. if (mSystem->mPtrSize == 4)
  4858. numElements++;
  4859. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  4860. {
  4861. numElements += mCompiler->mMaxInterfaceSlots;
  4862. auto maxIFaceVirtIdx = 0;
  4863. if (!typeInstance->IsInterface())
  4864. {
  4865. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4866. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4867. numElements += typeInstance->GetOrigVTableSize();
  4868. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  4869. if (typeInstance->mHotTypeData != NULL)
  4870. {
  4871. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4872. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4873. }
  4874. numElements += ifaceMethodLen;
  4875. }
  4876. if (outNumElements != NULL)
  4877. *outNumElements = numElements;
  4878. }
  4879. StringT<128> classVDataName;
  4880. String memberName = "sBfClassVData";
  4881. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  4882. {
  4883. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  4884. memberName += "_";
  4885. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  4886. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  4887. }
  4888. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  4889. if (outMangledName != NULL)
  4890. *outMangledName = classVDataName;
  4891. BfIRValue globalVariable;
  4892. if (globalVariablePtr != NULL)
  4893. {
  4894. globalVariable = *globalVariablePtr;
  4895. }
  4896. else
  4897. {
  4898. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4899. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4900. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4901. arrayType,
  4902. true,
  4903. BfIRLinkageType_External,
  4904. BfIRValue(),
  4905. classVDataName);
  4906. mClassVDataRefs[typeInstance] = globalVariable;
  4907. }
  4908. return globalVariable;
  4909. }
  4910. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4911. {
  4912. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4913. if (mIsComptimeModule)
  4914. return mBfIRBuilder->Comptime_GetBfType(typeInstance->mTypeId, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4915. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4916. }
  4917. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4918. {
  4919. if (mBfIRBuilder->mIgnoreWrites)
  4920. return mBfIRBuilder->GetFakeVal();
  4921. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4922. if (numElements < 0)
  4923. InternalError("CreateClassVDataExtGlobal numElements < 0");
  4924. if (numElements <= 0)
  4925. return BfIRValue();
  4926. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4927. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4928. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4929. BF_ASSERT(declTypeInst == implTypeInst);
  4930. else
  4931. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4932. if (declTypeInst != implTypeInst)
  4933. {
  4934. BfTypeInstance* highestImpl = declTypeInst;
  4935. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4936. {
  4937. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4938. break; // Start of an ext entry for another type
  4939. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4940. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4941. highestImpl = checkImplTypeInst;
  4942. }
  4943. if (highestImpl != implTypeInst)
  4944. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4945. }
  4946. BfVDataExtEntry mapEntry;
  4947. mapEntry.mDeclTypeInst = declTypeInst;
  4948. mapEntry.mImplTypeInst = implTypeInst;
  4949. BfIRValue* irValuePtr = NULL;
  4950. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4951. return *irValuePtr;
  4952. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4953. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4954. StringT<512> classVDataName;
  4955. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4956. if (declTypeInst != implTypeInst)
  4957. {
  4958. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4959. }
  4960. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4961. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4962. SizedArray<BfIRValue, 32> vData;
  4963. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4964. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4965. {
  4966. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4967. break; // Start of an ext entry for another type
  4968. BfIRValue vValue;
  4969. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4970. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4971. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4972. {
  4973. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4974. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4975. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4976. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4977. {
  4978. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4979. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4980. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4981. vValue = funcPtr;
  4982. }
  4983. }
  4984. if (!vValue)
  4985. vValue = voidPtrNull;
  4986. vData.Add(vValue);
  4987. }
  4988. BF_ASSERT((int)vData.size() == numElements);
  4989. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4990. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4991. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4992. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4993. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4994. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, vData);
  4995. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4996. mClassVDataExtRefs[mapEntry] = globalVariable;
  4997. return globalVariable;
  4998. }
  4999. BfIRValue BfModule::CreateTypeDataRef(BfType* type, bool forceConstant)
  5000. {
  5001. if (mBfIRBuilder->mIgnoreWrites)
  5002. {
  5003. return mBfIRBuilder->CreateTypeOf(type);
  5004. }
  5005. if (mIsComptimeModule)
  5006. {
  5007. if (forceConstant)
  5008. return mBfIRBuilder->CreateTypeOfComptime(type);
  5009. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  5010. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  5011. return mBfIRBuilder->Comptime_GetReflectType(type->mTypeId, mBfIRBuilder->MapType(typeTypeInst));
  5012. }
  5013. PopulateType(type);
  5014. BfIRValue globalVariable;
  5015. BfIRValue* globalVariablePtr = NULL;
  5016. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  5017. {
  5018. if (*globalVariablePtr)
  5019. return mBfIRBuilder->CreateTypeOf(type, *globalVariablePtr);
  5020. }
  5021. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  5022. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  5023. auto typeInstance = type->ToTypeInstance();
  5024. StringT<4096> typeDataName;
  5025. if (typeInstance != NULL)
  5026. {
  5027. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  5028. }
  5029. else
  5030. {
  5031. typeDataName += "sBfTypeData.";
  5032. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  5033. }
  5034. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  5035. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  5036. mBfIRBuilder->SetReflectTypeData(mBfIRBuilder->MapType(type), globalVariable);
  5037. mTypeDataRefs[type] = globalVariable;
  5038. return mBfIRBuilder->CreateTypeOf(type, globalVariable);
  5039. }
  5040. void BfModule::EncodeAttributeData(BfTypeInstance* typeInstance, BfType* argType, BfIRValue arg, SizedArrayImpl<uint8>& data, Dictionary<int, int>& usedStringIdMap)
  5041. {
  5042. #define PUSH_INT8(val) data.push_back((uint8)val)
  5043. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  5044. #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); }
  5045. #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); \
  5046. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  5047. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  5048. bool handled = false;
  5049. if (constant == NULL)
  5050. {
  5051. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  5052. return;
  5053. }
  5054. if (argType->IsObject())
  5055. {
  5056. if ((argType->IsInstanceOf(mCompiler->mStringTypeDef)) || (argType == mContext->mBfObjectType))
  5057. {
  5058. if (constant->mTypeCode == BfTypeCode_StringId)
  5059. {
  5060. int stringId = constant->mInt32;
  5061. int* orderedIdPtr;
  5062. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  5063. {
  5064. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  5065. }
  5066. GetStringObjectValue(stringId, true, true);
  5067. PUSH_INT8(0xFF); // String
  5068. PUSH_INT32(*orderedIdPtr);
  5069. return;
  5070. }
  5071. }
  5072. }
  5073. if (argType->IsPointer())
  5074. {
  5075. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  5076. {
  5077. if (constant->mTypeCode == BfTypeCode_StringId)
  5078. {
  5079. int stringId = constant->mInt32;
  5080. int* orderedIdPtr;
  5081. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  5082. {
  5083. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  5084. }
  5085. GetStringObjectValue(stringId, true, true);
  5086. PUSH_INT8(0xFF); // String
  5087. PUSH_INT32(*orderedIdPtr);
  5088. return;
  5089. }
  5090. }
  5091. }
  5092. if (constant->mConstType == BfConstType_BitCastNull)
  5093. {
  5094. PUSH_INT8(BfTypeCode_NullPtr);
  5095. return;
  5096. }
  5097. if (constant->mConstType == BfConstType_BitCast)
  5098. {
  5099. auto bitcast = (BfConstantBitCast*)constant;
  5100. EncodeAttributeData(typeInstance, argType, BfIRValue(BfIRValueFlags_Const, bitcast->mTarget), data, usedStringIdMap);
  5101. return;
  5102. }
  5103. PUSH_INT8(constant->mTypeCode);
  5104. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  5105. (constant->mTypeCode == BfTypeCode_UInt64) ||
  5106. (constant->mTypeCode == BfTypeCode_Double))
  5107. {
  5108. PUSH_INT64(constant->mInt64);
  5109. }
  5110. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  5111. (constant->mTypeCode == BfTypeCode_UInt32) ||
  5112. (constant->mTypeCode == BfTypeCode_Char32))
  5113. {
  5114. PUSH_INT32(constant->mInt32);
  5115. }
  5116. else if (constant->mTypeCode == BfTypeCode_Float)
  5117. {
  5118. float val = (float)constant->mDouble;
  5119. PUSH_INT32(*(int*)&val);
  5120. }
  5121. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  5122. (constant->mTypeCode == BfTypeCode_UInt16) ||
  5123. (constant->mTypeCode == BfTypeCode_Char16))
  5124. {
  5125. PUSH_INT16(constant->mInt16);
  5126. }
  5127. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  5128. (constant->mTypeCode == BfTypeCode_UInt8) ||
  5129. (constant->mTypeCode == BfTypeCode_Boolean) ||
  5130. (constant->mTypeCode == BfTypeCode_Char8))
  5131. {
  5132. PUSH_INT8(constant->mInt8);
  5133. }
  5134. else if (constant->mConstType == BfConstType_TypeOf)
  5135. {
  5136. auto typeOf = (BfTypeOf_Const*)constant;
  5137. PUSH_INT32(typeOf->mType->mTypeId);
  5138. }
  5139. else if (constant->mConstType == BfConstType_AggZero)
  5140. {
  5141. for (int i = 0; i < argType->mSize; i++)
  5142. data.Add(0);
  5143. }
  5144. else if (constant->mConstType == BfConstType_Box)
  5145. {
  5146. auto box = (BfConstantBox*)constant;
  5147. PUSH_INT32(box->mToType.mId);
  5148. BfType* resultType = NULL;
  5149. if (box->mToType.mKind == BfIRTypeData::TypeKind_TypeId)
  5150. resultType = mContext->FindTypeById(box->mToType.mId);
  5151. if ((resultType != NULL) && (resultType->IsBoxed()))
  5152. {
  5153. auto boxedType = (BfBoxedType*)resultType;
  5154. int dataOffset = 0;
  5155. if (!boxedType->mFieldInstances.IsEmpty())
  5156. dataOffset = BF_MAX(boxedType->mFieldInstances.back().mDataOffset, 0);
  5157. int dataSize = boxedType->mInstSize - dataOffset;
  5158. for (int i = 0; i < dataSize; i++)
  5159. data.Add(0);
  5160. typeInstance->mConstHolder->WriteConstant(BfIRValue(BfIRValueFlags_Const, box->mTarget), &data[data.mSize - dataSize], boxedType->GetUnderlyingType());
  5161. return;
  5162. }
  5163. //int dataOffset =
  5164. //mBfIRBuilder->WriteConstant()
  5165. // BfType* resultType = NULL;
  5166. // if (box->mToType.mKind == BfIRTypeData::TypeKind_TypeId)
  5167. // resultType = mContext->FindTypeById(box->mToType.mId);
  5168. //
  5169. // if ((resultType != NULL) && (resultType->IsBoxed()))
  5170. // {
  5171. // auto boxedType = (BfBoxedType*)resultType;
  5172. // EncodeAttributeData(typeInstance, boxedType->GetUnderlyingType(), BfIRValue(BfIRValueFlags_Const, box->mTarget), data, usedStringIdMap);
  5173. // return;
  5174. // }
  5175. Fail(StrFormat("Unhandled constant box in '%s'", TypeToString(typeInstance).c_str()));
  5176. }
  5177. // else if (constant->mConstType == BfConstType_Agg)
  5178. // {
  5179. // BF_ASSERT(argType->IsComposite());
  5180. // if (argType->IsSizedArray())
  5181. // {
  5182. // auto argSizedArrayType = (BfSizedArrayType*)argType;
  5183. // }
  5184. // else
  5185. // {
  5186. // auto argTypeInstance = argType->ToTypeInstance();
  5187. // }
  5188. // }
  5189. else
  5190. {
  5191. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  5192. }
  5193. }
  5194. BfIRValue BfModule::CreateFieldData(BfFieldInstance* fieldInstance, int customAttrIdx)
  5195. {
  5196. bool isComptimeArg = mBfIRBuilder->mIgnoreWrites;
  5197. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5198. auto typeInstance = fieldInstance->mOwner;
  5199. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5200. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5201. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5202. BfType* typeIdType = intType;
  5203. BfTypeInstance* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef)->ToTypeInstance();
  5204. BfIRValue emptyValueType = mBfIRBuilder->mIgnoreWrites ?
  5205. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>()) :
  5206. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>());
  5207. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, !mIsComptimeModule);
  5208. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  5209. int typeId = 0;
  5210. auto fieldType = fieldInstance->GetResolvedType();
  5211. if (fieldType->IsGenericParam())
  5212. {
  5213. //TODO:
  5214. }
  5215. else
  5216. typeId = fieldType->mTypeId;
  5217. BfFieldFlags fieldFlags = (BfFieldFlags)0;
  5218. if (fieldDef->mProtection == BfProtection_Protected)
  5219. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Protected);
  5220. if (fieldDef->mProtection == BfProtection_Public)
  5221. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Public);
  5222. if (fieldDef->mIsStatic)
  5223. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Static);
  5224. if (fieldDef->mIsConst)
  5225. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Const);
  5226. if (fieldDef->IsEnumCaseEntry())
  5227. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_EnumCase);
  5228. if (fieldDef->mIsReadOnly)
  5229. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_ReadOnly);
  5230. if (fieldInstance->IsAppendedObject())
  5231. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Appended);
  5232. BfIRValue constValue;
  5233. BfIRValue constValue2;
  5234. if (fieldInstance->mIsEnumPayloadCase)
  5235. {
  5236. int tagId = -fieldInstance->mDataIdx - 1;
  5237. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, tagId);
  5238. }
  5239. else if (fieldInstance->GetFieldDef()->mIsConst)
  5240. {
  5241. if (fieldInstance->mConstIdx != -1)
  5242. {
  5243. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  5244. uint64 val = constant->mUInt64;
  5245. if (constant->mTypeCode == BfTypeCode_Float)
  5246. {
  5247. float f = (float)*(double*)&val;
  5248. val = *(uint32*)&f;
  5249. }
  5250. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5251. if (is32Bit)
  5252. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val >> 32);
  5253. }
  5254. }
  5255. else if (fieldInstance->GetFieldDef()->mIsStatic)
  5256. {
  5257. BfTypedValue refVal;
  5258. if (mIsComptimeModule)
  5259. {
  5260. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mFieldIdx);
  5261. }
  5262. else
  5263. {
  5264. refVal = ReferenceStaticField(fieldInstance);
  5265. }
  5266. if (refVal.mValue.IsConst())
  5267. {
  5268. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  5269. if (constant->mConstType == BfConstType_GlobalVar)
  5270. {
  5271. auto globalVar = (BfGlobalVar*)constant;
  5272. if (globalVar->mName[0] == '#')
  5273. refVal = BfTypedValue();
  5274. }
  5275. }
  5276. if (!isComptimeArg)
  5277. {
  5278. if (refVal.IsAddr())
  5279. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5280. else if ((fieldInstance->IsAppendedObject()) && (refVal))
  5281. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5282. }
  5283. }
  5284. if (!constValue)
  5285. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  5286. BfIRValue result;
  5287. if (is32Bit)
  5288. {
  5289. if (!constValue2)
  5290. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  5291. SizedArray<BfIRValue, 8> fieldVals =
  5292. {
  5293. emptyValueType,
  5294. fieldNameConst, // mName
  5295. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5296. constValue, // mData
  5297. constValue2, // mDataHi
  5298. GetConstValue(fieldFlags, shortType), // mFlags
  5299. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5300. };
  5301. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5302. result = isComptimeArg ?
  5303. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5304. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5305. }
  5306. else
  5307. {
  5308. SizedArray<BfIRValue, 8> fieldVals =
  5309. {
  5310. emptyValueType,
  5311. fieldNameConst, // mName
  5312. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5313. constValue, // mData
  5314. GetConstValue(fieldFlags, shortType), // mFlags
  5315. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5316. };
  5317. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5318. result = isComptimeArg ?
  5319. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5320. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5321. }
  5322. return result;
  5323. }
  5324. void BfModule::CreateSlotOfs(BfTypeInstance* typeInstance)
  5325. {
  5326. int virtSlotIdx = -1;
  5327. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5328. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5329. // For interfaces we ONLY emit the slot num
  5330. StringT<512> slotVarName;
  5331. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  5332. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  5333. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  5334. GetConstValue32(virtSlotIdx), slotVarName);
  5335. }
  5336. BfIRValue BfModule::GetTypeTypeData(BfType* type, BfCreateTypeDataContext& ctx, bool needsTypeData, bool wantsTypeDecl, bool needsTypeNames, int& typeFlags, int& typeCode)
  5337. {
  5338. BfTypeInstance* typeInstance = type->ToTypeInstance();
  5339. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  5340. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  5341. BfIRValue typeTypeData;
  5342. if (needsTypeData)
  5343. {
  5344. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  5345. BfTypeInstance* typeDataSource = NULL;
  5346. if (typeInstance != NULL)
  5347. {
  5348. if (typeInstance->IsUnspecializedType())
  5349. {
  5350. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  5351. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  5352. }
  5353. else if (typeInstance->IsArray())
  5354. {
  5355. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  5356. typeFlags |= BfTypeFlags_Array;
  5357. }
  5358. else if (typeInstance->IsGenericTypeInstance())
  5359. {
  5360. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  5361. typeFlags |= BfTypeFlags_SpecializedGeneric;
  5362. }
  5363. else
  5364. typeDataSource = typeInstanceTypeInstance;
  5365. }
  5366. else if (type->IsPointer())
  5367. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5368. else if (type->IsRef())
  5369. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5370. else if (type->IsSizedArray())
  5371. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5372. else if (type->IsConstExprValue())
  5373. typeDataSource = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5374. else if (type->IsGenericParam())
  5375. {
  5376. typeFlags |= BfTypeFlags_GenericParam;
  5377. typeDataSource = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5378. }
  5379. else
  5380. typeDataSource = mContext->mBfTypeType;
  5381. if (wantsTypeDecl)
  5382. {
  5383. typeDataSource = ResolveTypeDef(mCompiler->mTypeTypeDeclDef)->ToTypeInstance();
  5384. }
  5385. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type) && (!mIsComptimeModule))
  5386. {
  5387. CreateTypeData(typeDataSource, ctx, false, true, needsTypeNames, true);
  5388. }
  5389. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  5390. ctx.mReflectTypeSet.Add(typeDataSource);
  5391. }
  5392. else
  5393. {
  5394. //typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  5395. typeTypeData = mBfIRBuilder->CreateConstNull();
  5396. }
  5397. if (typeInstance != NULL)
  5398. {
  5399. BF_ASSERT((type->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || mIsComptimeModule);
  5400. typeCode = typeInstance->mTypeDef->mTypeCode;
  5401. if (typeInstance->IsBoxed())
  5402. typeCode = BfTypeCode_Object;
  5403. }
  5404. else if (type->IsPrimitiveType())
  5405. {
  5406. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  5407. typeCode = primType->mTypeDef->mTypeCode;
  5408. }
  5409. else if (type->IsPointer())
  5410. {
  5411. typeCode = BfTypeCode_Pointer;
  5412. typeFlags |= BfTypeFlags_Pointer;
  5413. }
  5414. else if (type->IsRef())
  5415. {
  5416. typeCode = BfTypeCode_Pointer;
  5417. typeFlags |= BfTypeFlags_Pointer;
  5418. }
  5419. if (type->IsObject())
  5420. {
  5421. typeFlags |= BfTypeFlags_Object;
  5422. if ((!wantsTypeDecl) && (typeInstance->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted))
  5423. {
  5424. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  5425. if ((methodInstance != NULL) && (methodInstance->GetOwner() != mContext->mBfObjectType))
  5426. typeFlags |= BfTypeFlags_HasDestructor;
  5427. }
  5428. }
  5429. if (type->IsStruct())
  5430. typeFlags |= BfTypeFlags_Struct;
  5431. if (type->IsInterface())
  5432. typeFlags |= BfTypeFlags_Interface;
  5433. if (type->IsBoxed())
  5434. {
  5435. typeFlags |= BfTypeFlags_Boxed;
  5436. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  5437. typeFlags |= BfTypeFlags_Pointer;
  5438. }
  5439. if (type->IsPrimitiveType())
  5440. typeFlags |= BfTypeFlags_Primitive;
  5441. if (type->IsTypedPrimitive())
  5442. typeFlags |= BfTypeFlags_TypedPrimitive;
  5443. if (type->IsTuple())
  5444. typeFlags |= BfTypeFlags_Tuple;
  5445. if (type->IsNullable())
  5446. typeFlags |= BfTypeFlags_Nullable;
  5447. if (type->IsSizedArray())
  5448. typeFlags |= BfTypeFlags_SizedArray;
  5449. if (type->IsConstExprValue())
  5450. typeFlags |= BfTypeFlags_ConstExpr;
  5451. if ((!wantsTypeDecl) && (type->IsSplattable()))
  5452. typeFlags |= BfTypeFlags_Splattable;
  5453. if (type->IsUnion())
  5454. typeFlags |= BfTypeFlags_Union;
  5455. if (type->IsDelegate())
  5456. typeFlags |= BfTypeFlags_Delegate;
  5457. if (type->IsFunction())
  5458. typeFlags |= BfTypeFlags_Function;
  5459. if ((!wantsTypeDecl) && (type->mDefineState != BfTypeDefineState_CETypeInit) && (type->WantsGCMarking()))
  5460. typeFlags |= BfTypeFlags_WantsMarking;
  5461. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsStatic))
  5462. typeFlags |= BfTypeFlags_Static;
  5463. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  5464. typeFlags |= BfTypeFlags_Abstract;
  5465. if ((typeInstance != NULL) && (typeInstance->mHasAppendWantMark))
  5466. typeFlags |= BfTypeFlags_HasAppendWantMark;
  5467. return typeTypeData;
  5468. }
  5469. BfIRValue BfModule::CreateTypeDeclData(BfType* type, BfProject* curProject)
  5470. {
  5471. auto typeDeclType = ResolveTypeDef(mCompiler->mTypeTypeDeclDef)->ToTypeInstance();
  5472. int typeCode = 0;
  5473. int typeFlags = 0;
  5474. BfCreateTypeDataContext createTypeDataCtx;
  5475. BfIRValue typeTypeData = GetTypeTypeData(type, createTypeDataCtx, true, true, true, typeFlags, typeCode);
  5476. SizedArray<BfIRValue, 4> typeValueParams;
  5477. GetConstClassValueParam(typeTypeData, typeValueParams);
  5478. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5479. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5480. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5481. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5482. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5483. BfType* typeIdType = intType;
  5484. auto typeInst = type->ToTypeInstance();
  5485. auto outerType = GetOuterType(type);
  5486. BfType* baseType = NULL;
  5487. if (typeInst != NULL)
  5488. baseType = typeInst->mBaseType;
  5489. enum BfTypeDeclFlags
  5490. {
  5491. BfTypeDeclFlag_DeclaredInDependency = 1,
  5492. BfTypeDeclFlag_DeclaredInDependent = 2,
  5493. BfTypeDeclFlag_DeclaredInCurrent = 4,
  5494. BfTypeDeclFlag_AlwaysVisible = 8,
  5495. BfTypeDeclFlag_SometimesVisible = 0x10
  5496. };
  5497. int flags = 0;
  5498. if (typeInst != NULL)
  5499. {
  5500. auto declProject = typeInst->mTypeDef->mProject;
  5501. auto depKind = curProject->GetDependencyKind(declProject);
  5502. if (depKind == BfProject::DependencyKind_Identity)
  5503. {
  5504. flags |= BfTypeDeclFlag_DeclaredInCurrent | BfTypeDeclFlag_AlwaysVisible | BfTypeDeclFlag_SometimesVisible;
  5505. }
  5506. else if (depKind == BfProject::DependencyKind_Dependency)
  5507. {
  5508. flags |= BfTypeDeclFlag_DeclaredInDependency | BfTypeDeclFlag_AlwaysVisible | BfTypeDeclFlag_SometimesVisible;
  5509. }
  5510. else if (depKind == BfProject::DependencyKind_Dependent_Exclusive)
  5511. {
  5512. flags |= BfTypeDeclFlag_DeclaredInDependent | BfTypeDeclFlag_AlwaysVisible | BfTypeDeclFlag_SometimesVisible;
  5513. }
  5514. else if (depKind == BfProject::DependencyKind_Dependent_Shared)
  5515. {
  5516. flags |= BfTypeDeclFlag_DeclaredInDependent | BfTypeDeclFlag_SometimesVisible;
  5517. }
  5518. }
  5519. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5520. SizedArray<BfIRValue, 9> typeDataParams =
  5521. {
  5522. objectData,
  5523. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5524. GetConstValue((outerType != NULL) ? outerType->mTypeId : 0, typeIdType), // mOuterTypeId
  5525. GetConstValue(typeFlags, intType), // mTypeFlags
  5526. GetConstValue(flags, byteType), // mFlags
  5527. GetConstValue(typeCode, byteType), // mTypeCode
  5528. };
  5529. FixConstValueParams(typeDeclType, typeDataParams);
  5530. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(typeDeclType, BfIRPopulateType_Full), typeDataParams);
  5531. String typeDataName = StrFormat("sBfTypeDeclData.%d", type->mTypeId);
  5532. BfIRValue typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeDeclType), true,
  5533. BfIRLinkageType_External, typeData, typeDataName);
  5534. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5535. return typeDataVar;
  5536. }
  5537. BfIRValue BfModule::CreateTypeData(BfType* type, BfCreateTypeDataContext& ctx, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  5538. {
  5539. if ((IsHotCompile()) && (!type->mDirty))
  5540. return BfIRValue();
  5541. BfIRValue* irValuePtr = NULL;
  5542. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  5543. {
  5544. return *irValuePtr;
  5545. }
  5546. BfTypeInstance* typeInstance = type->ToTypeInstance();
  5547. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  5548. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  5549. if (typeInstanceType == NULL)
  5550. {
  5551. AssertErrorState();
  5552. return BfIRValue();
  5553. }
  5554. int typeCode = BfTypeCode_None;
  5555. int typeFlags = 0;
  5556. BfIRValue typeTypeData = GetTypeTypeData(type, ctx, needsTypeData, false, needsTypeNames, typeFlags, typeCode);
  5557. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5558. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5559. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5560. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5561. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5562. BfType* typeIdType = intType;
  5563. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  5564. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  5565. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  5566. auto voidPtrNull = GetDefaultValue(voidPtrType);
  5567. SizedArray<BfIRValue, 4> typeValueParams;
  5568. GetConstClassValueParam(typeTypeData, typeValueParams);
  5569. FixConstValueParams(mContext->mBfObjectType, typeValueParams);
  5570. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5571. StringT<512> typeDataName;
  5572. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  5573. {
  5574. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  5575. if (typeInstance->mTypeDef->IsGlobalsContainer())
  5576. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  5577. }
  5578. else
  5579. {
  5580. typeDataName += "sBfTypeData.";
  5581. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  5582. }
  5583. int virtSlotIdx = -1;
  5584. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5585. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5586. int memberDataOffset = 0;
  5587. if (type->IsInterface())
  5588. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  5589. else if (typeInstance != NULL)
  5590. {
  5591. for (auto& fieldInstance : typeInstance->mFieldInstances)
  5592. {
  5593. if (fieldInstance.mDataOffset != -1)
  5594. {
  5595. memberDataOffset = fieldInstance.mDataOffset;
  5596. break;
  5597. }
  5598. }
  5599. }
  5600. int boxedTypeId = 0;
  5601. if ((type->IsValueType()) || (type->IsWrappableType()))
  5602. {
  5603. auto boxedType = CreateBoxedType(type, false);
  5604. if ((boxedType != NULL) && (boxedType->mIsReified))
  5605. boxedTypeId = boxedType->mTypeId;
  5606. }
  5607. int stackCount = 0;
  5608. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx >= 0))
  5609. {
  5610. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5611. if (typeOptions->mAllocStackTraceDepth != -1)
  5612. stackCount = BF_MIN(0xFF, BF_MAX(0x01, typeOptions->mAllocStackTraceDepth));
  5613. }
  5614. SizedArray<BfIRValue, 9> typeDataParams =
  5615. {
  5616. objectData,
  5617. GetConstValue(type->mSize, intType), // mSize
  5618. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5619. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  5620. GetConstValue(typeFlags, intType), // mTypeFlags
  5621. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  5622. GetConstValue(typeCode, byteType), // mTypeCode
  5623. GetConstValue(type->mAlign, byteType), // mAlign
  5624. GetConstValue(stackCount, byteType), // mAllocStackCountOverride
  5625. };
  5626. FixConstValueParams(mContext->mBfTypeType, typeDataParams);
  5627. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  5628. if (typeInstance == NULL)
  5629. {
  5630. BfIRValue typeDataVar;
  5631. if (needsTypeData)
  5632. {
  5633. if (type->IsPointer())
  5634. {
  5635. auto pointerType = (BfPointerType*)type;
  5636. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  5637. {
  5638. typeData,
  5639. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  5640. };
  5641. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5642. FixConstValueParams(reflectPointerType, pointerTypeDataParms);
  5643. auto pointerTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  5644. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  5645. BfIRLinkageType_External, pointerTypeData, typeDataName);
  5646. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5647. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5648. }
  5649. else if (type->IsRef())
  5650. {
  5651. auto refType = (BfRefType*)type;
  5652. SizedArray<BfIRValue, 3> refTypeDataParms =
  5653. {
  5654. typeData,
  5655. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  5656. GetConstValue((int8)refType->mRefKind, byteType),
  5657. };
  5658. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5659. FixConstValueParams(reflectRefType, refTypeDataParms);
  5660. auto refTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  5661. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  5662. BfIRLinkageType_External, refTypeData, typeDataName);
  5663. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5664. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5665. }
  5666. else if (type->IsSizedArray())
  5667. {
  5668. auto sizedArrayType = (BfSizedArrayType*)type;
  5669. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  5670. {
  5671. typeData,
  5672. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  5673. GetConstValue(sizedArrayType->mElementCount, intType)
  5674. };
  5675. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5676. FixConstValueParams(reflectSizedArrayType, sizedArrayTypeDataParms);
  5677. auto sizedArrayTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  5678. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  5679. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  5680. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5681. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5682. }
  5683. else if (type->IsConstExprValue())
  5684. {
  5685. auto constExprType = (BfConstExprValueType*)type;
  5686. SizedArray<BfIRValue, 3> constExprTypeDataParms =
  5687. {
  5688. typeData,
  5689. GetConstValue(constExprType->mType->mTypeId, typeIdType),
  5690. GetConstValue(constExprType->mValue.mInt64, longType)
  5691. };
  5692. auto reflectConstExprType = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5693. FixConstValueParams(reflectConstExprType, constExprTypeDataParms);
  5694. auto ConstExprTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectConstExprType, BfIRPopulateType_Full), constExprTypeDataParms);
  5695. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectConstExprType), true,
  5696. BfIRLinkageType_External, ConstExprTypeData, typeDataName);
  5697. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5698. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5699. }
  5700. else if (type->IsGenericParam())
  5701. {
  5702. auto genericParamType = (BfGenericParamType*)type;
  5703. SizedArray<BfIRValue, 3> genericParamTypeDataParms =
  5704. {
  5705. typeData
  5706. };
  5707. auto reflectGenericParamType = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5708. FixConstValueParams(reflectGenericParamType, genericParamTypeDataParms);
  5709. auto genericParamTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectGenericParamType, BfIRPopulateType_Full), genericParamTypeDataParms);
  5710. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectGenericParamType), true,
  5711. BfIRLinkageType_External, genericParamTypeData, typeDataName);
  5712. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5713. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5714. }
  5715. else
  5716. {
  5717. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  5718. BfIRLinkageType_External, typeData, typeDataName);
  5719. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5720. }
  5721. }
  5722. else
  5723. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5724. mTypeDataRefs[type] = typeDataVar;
  5725. return typeDataVar;
  5726. }
  5727. // Reserve position
  5728. mTypeDataRefs[typeInstance] = BfIRValue();
  5729. if ((typeInstance->IsReified()) && (!mIsComptimeModule))
  5730. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5731. BfTypeDef* typeDef = typeInstance->mTypeDef;
  5732. StringT<512> mangledName;
  5733. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  5734. if (!mIsComptimeModule)
  5735. {
  5736. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5737. {
  5738. auto methodDef = typeDef->mMethods[methodIdx];
  5739. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  5740. if (methodInstance == NULL)
  5741. continue;
  5742. if (typeInstance->IsUnspecializedType())
  5743. continue;
  5744. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5745. {
  5746. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  5747. {
  5748. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  5749. // We need to create an empty thunk for this chained method
  5750. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  5751. mBfIRBuilder->SetActiveFunction(func);
  5752. auto block = mBfIRBuilder->CreateBlock("entry", true);
  5753. mBfIRBuilder->SetInsertPoint(block);
  5754. mBfIRBuilder->CreateRetVoid();
  5755. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  5756. }
  5757. }
  5758. }
  5759. }
  5760. SizedArray<BfIRValue, 32> vData;
  5761. BfIRValue classVDataVar;
  5762. String classVDataName;
  5763. if (typeInstance->mSlotNum >= 0)
  5764. {
  5765. CreateSlotOfs(typeInstance);
  5766. }
  5767. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  5768. {
  5769. int dynCastDataElems = 0;
  5770. int numElements = 1;
  5771. int vDataOfs = mCompiler->GetVDataPrefixDataCount(); // The number of intptrs before the iface slot map
  5772. numElements += mCompiler->mMaxInterfaceSlots;
  5773. if (!typeInstance->IsInterface())
  5774. {
  5775. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  5776. numElements += mCompiler->GetDynCastVDataCount();
  5777. numElements += typeInstance->mVirtualMethodTableSize;
  5778. }
  5779. int expectNumElements = 0;
  5780. if (!typeDef->mIsStatic)
  5781. {
  5782. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  5783. }
  5784. for (int i = 0; i < mCompiler->GetVDataPrefixDataCount(); i++)
  5785. vData.push_back(BfIRValue()); // Type
  5786. SizedArray<BfIRValue, 1> extVTableData;
  5787. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  5788. if (!typeInstance->IsInterface())
  5789. {
  5790. Array<int32> dynCastData;
  5791. if (typeInstance->IsBoxed())
  5792. {
  5793. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  5794. dynCastData.Add(underlyingType->mInheritanceId);
  5795. }
  5796. else
  5797. dynCastData.Add(typeInstance->mInheritanceId);
  5798. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  5799. dynCastData.Add(0);
  5800. dynCastData.Add(0);
  5801. auto checkTypeInst = typeInstance;
  5802. while (checkTypeInst != NULL)
  5803. {
  5804. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5805. {
  5806. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  5807. {
  5808. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  5809. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  5810. }
  5811. }
  5812. checkTypeInst = checkTypeInst->GetImplBaseType();
  5813. }
  5814. if (mSystem->mPtrSize == 8)
  5815. {
  5816. int intPtrCount = (dynCastDataElems + 1) / 2;
  5817. vDataOfs += intPtrCount;
  5818. uint64* intPtrData = (uint64*)&dynCastData[0];
  5819. for (int i = 0; i < intPtrCount; i++)
  5820. {
  5821. uint64 val = intPtrData[i];
  5822. if (val == 0)
  5823. {
  5824. vData.push_back(voidPtrNull);
  5825. }
  5826. else
  5827. {
  5828. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5829. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5830. }
  5831. }
  5832. }
  5833. else
  5834. {
  5835. int intPtrCount = dynCastDataElems;
  5836. vDataOfs += intPtrCount;
  5837. uint32* intPtrData = (uint32*)&dynCastData[0];
  5838. for (int i = 0; i < intPtrCount; i++)
  5839. {
  5840. uint32 val = intPtrData[i];
  5841. if (val == 0)
  5842. {
  5843. vData.push_back(voidPtrNull);
  5844. }
  5845. else
  5846. {
  5847. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  5848. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5849. }
  5850. }
  5851. }
  5852. }
  5853. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  5854. vData.push_back(voidPtrNull);
  5855. struct _InterfaceMatchEntry
  5856. {
  5857. BfTypeInterfaceEntry* mEntry;
  5858. BfTypeInstance* mEntrySource;
  5859. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  5860. };
  5861. int highestIFaceVirtIdx = 0;
  5862. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  5863. auto checkTypeInst = typeInstance;
  5864. bool forceInterfaceSet = false;
  5865. while (checkTypeInst != NULL)
  5866. {
  5867. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5868. {
  5869. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  5870. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject)))
  5871. continue;
  5872. _InterfaceMatchEntry* matchEntry = NULL;
  5873. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  5874. {
  5875. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  5876. if (compareCheckTypeInst->IsBoxed())
  5877. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  5878. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  5879. if (compareEntrySource->IsBoxed())
  5880. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  5881. auto prevEntry = matchEntry->mEntry;
  5882. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  5883. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  5884. if ((!isBetter) && (!isWorse))
  5885. {
  5886. // Unboxed comparison to Object fix
  5887. if (compareCheckTypeInst == mContext->mBfObjectType)
  5888. isWorse = true;
  5889. else if (compareEntrySource == mContext->mBfObjectType)
  5890. isBetter = true;
  5891. }
  5892. if (forceInterfaceSet)
  5893. {
  5894. isBetter = true;
  5895. isWorse = false;
  5896. }
  5897. if (isBetter == isWorse)
  5898. CompareDeclTypes(checkTypeInst, interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  5899. if (isBetter == isWorse)
  5900. {
  5901. if (matchEntry->mAmbiguousEntries.empty())
  5902. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  5903. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  5904. continue;
  5905. }
  5906. else if (isBetter)
  5907. {
  5908. matchEntry->mEntry = &interfaceEntry;
  5909. matchEntry->mEntrySource = checkTypeInst;
  5910. matchEntry->mAmbiguousEntries.Clear();
  5911. }
  5912. else
  5913. continue;
  5914. }
  5915. else
  5916. {
  5917. _InterfaceMatchEntry matchEntry;
  5918. matchEntry.mEntry = &interfaceEntry;
  5919. matchEntry.mEntrySource = checkTypeInst;
  5920. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  5921. }
  5922. }
  5923. checkTypeInst = checkTypeInst->GetImplBaseType();
  5924. }
  5925. for (auto interfacePair : interfaceMap)
  5926. {
  5927. auto& interfaceMatchEntry = interfacePair.mValue;
  5928. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  5929. {
  5930. 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());
  5931. if (error != NULL)
  5932. {
  5933. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  5934. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  5935. }
  5936. }
  5937. }
  5938. if ((!mIsComptimeModule) && (!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  5939. {
  5940. int startTabIdx = (int)vData.size();
  5941. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  5942. BfTypeInstance* checkTypeInst = typeInstance;
  5943. while (checkTypeInst != NULL)
  5944. {
  5945. origVirtTypeStack.push_back(checkTypeInst);
  5946. checkTypeInst = checkTypeInst->GetImplBaseType();
  5947. }
  5948. Array<BfVirtualMethodEntry> origVTable;
  5949. int origVirtIdx = 0;
  5950. if (typeInstance->mTypeDef->mIsCombinedPartial)
  5951. {
  5952. HashSet<String> reslotNames;
  5953. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5954. {
  5955. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5956. if (entry.mDeclaringMethod.mMethodNum == -1)
  5957. continue;
  5958. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5959. if ((methodInstance == NULL) ||
  5960. ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))))
  5961. {
  5962. if (origVTable.empty())
  5963. origVTable = typeInstance->mVirtualMethodTable;
  5964. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  5965. if (declMethodInstance != NULL)
  5966. {
  5967. if ((mIsComptimeModule) || (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject)))
  5968. {
  5969. // Prepare to reslot...
  5970. entry.mImplementingMethod = entry.mDeclaringMethod;
  5971. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  5972. }
  5973. else
  5974. {
  5975. // Decl isn't accessible, null out entry
  5976. entry.mImplementingMethod = BfMethodRef();
  5977. }
  5978. }
  5979. }
  5980. }
  5981. if (!reslotNames.IsEmpty())
  5982. {
  5983. BfAmbiguityContext ambiguityContext;
  5984. ambiguityContext.mTypeInstance = typeInstance;
  5985. ambiguityContext.mModule = this;
  5986. ambiguityContext.mIsProjectSpecific = true;
  5987. ambiguityContext.mIsReslotting = true;
  5988. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5989. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  5990. {
  5991. auto methodInstance = methodGroup.mDefault;
  5992. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  5993. continue;
  5994. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  5995. continue;
  5996. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  5997. continue;
  5998. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  5999. continue;
  6000. SlotVirtualMethod(methodInstance, &ambiguityContext);
  6001. }
  6002. ambiguityContext.Finish();
  6003. }
  6004. }
  6005. bool isInExts = false;
  6006. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  6007. {
  6008. BfIRValue vValue = voidPtrNull;
  6009. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  6010. BfModuleMethodInstance moduleMethodInst;
  6011. if (entry.mDeclaringMethod.mMethodNum == -1)
  6012. {
  6013. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  6014. isInExts = true;
  6015. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  6016. if (vExt)
  6017. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  6018. }
  6019. else
  6020. {
  6021. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  6022. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  6023. {
  6024. if (entry.mImplementingMethod.mMethodNum >= 0)
  6025. {
  6026. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  6027. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  6028. }
  6029. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  6030. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  6031. {
  6032. BF_ASSERT((mIsComptimeModule) || typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  6033. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6034. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  6035. vValue = funcPtr;
  6036. }
  6037. }
  6038. }
  6039. while (origVirtTypeStack.size() != 0)
  6040. {
  6041. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  6042. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  6043. {
  6044. // Moved past current base vtable size
  6045. origVirtTypeStack.pop_back();
  6046. continue;
  6047. }
  6048. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  6049. {
  6050. // We are within the original vtable size
  6051. int idx = startTabIdx + origVirtIdx;
  6052. origVirtIdx++;
  6053. vData.push_back(vValue);
  6054. }
  6055. else
  6056. {
  6057. // This is a new entry, it only gets added to the ext
  6058. BF_ASSERT(isInExts);
  6059. }
  6060. break;
  6061. }
  6062. }
  6063. if (!origVTable.empty())
  6064. typeInstance->mVirtualMethodTable = origVTable;
  6065. }
  6066. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  6067. if (typeInstance->mHotTypeData != NULL)
  6068. {
  6069. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  6070. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  6071. }
  6072. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  6073. int iFaceMethodStartIdx = (int)vData.size();
  6074. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  6075. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  6076. vData[i] = voidPtrNull;
  6077. if (expectNumElements != 0)
  6078. BF_ASSERT(expectNumElements == vData.size());
  6079. //BF_ASSERT(vData.size() == expectNumElements);
  6080. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  6081. // ifaceMethodExtData.Add(voidPtrNull);
  6082. int ifaceEntryIdx = iFaceMethodStartIdx;
  6083. for (auto& interfacePair : interfaceMap)
  6084. {
  6085. auto interfaceEntry = interfacePair.mValue.mEntry;
  6086. if (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  6087. {
  6088. BF_ASSERT(mIsComptimeModule);
  6089. break;
  6090. }
  6091. bool makeEmpty = false;
  6092. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject)))
  6093. makeEmpty = true;
  6094. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  6095. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  6096. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6097. {
  6098. BfIRValue pushValue;
  6099. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  6100. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  6101. continue;
  6102. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  6103. continue;
  6104. if (makeEmpty)
  6105. {
  6106. pushValue = voidPtrNull;
  6107. }
  6108. else
  6109. {
  6110. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  6111. auto methodInstance = (BfMethodInstance*)methodRef;
  6112. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  6113. {
  6114. BF_ASSERT(methodInstance->mIsReified);
  6115. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  6116. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  6117. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  6118. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  6119. pushValue = funcPtr;
  6120. }
  6121. else
  6122. {
  6123. pushValue = voidPtrNull;
  6124. }
  6125. }
  6126. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  6127. if (idx < ifaceMethodExtStart)
  6128. {
  6129. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  6130. vData[iFaceMethodStartIdx + idx] = pushValue;
  6131. }
  6132. else
  6133. {
  6134. BF_ASSERT(useExt);
  6135. int extIdx = idx - ifaceMethodExtStart;
  6136. while (extIdx >= ifaceMethodExtData.size())
  6137. ifaceMethodExtData.Add(voidPtrNull);
  6138. ifaceMethodExtData[extIdx] = pushValue;
  6139. }
  6140. }
  6141. }
  6142. if (typeInstance->IsBoxed())
  6143. {
  6144. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  6145. if (boxedType->IsBoxedStructPtr())
  6146. {
  6147. // Force override of GetHashCode so we use the pointer address as the hash code
  6148. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  6149. // Force override of GetHashCode so we use the pointer address as the hash code
  6150. for (auto& checkIFace : checkTypeInst->mInterfaces)
  6151. {
  6152. if (checkIFace.mStartVirtualIdx < 0)
  6153. continue;
  6154. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6155. {
  6156. BfIRValue pushValue;
  6157. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  6158. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  6159. continue;
  6160. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  6161. continue;
  6162. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  6163. auto methodInstance = (BfMethodInstance*)methodRef;
  6164. BF_ASSERT(methodInstance->mIsReified);
  6165. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  6166. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  6167. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  6168. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  6169. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  6170. vData[iFaceMethodStartIdx + idx] = funcPtr;
  6171. }
  6172. }
  6173. }
  6174. }
  6175. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic) && (!mIsComptimeModule))
  6176. {
  6177. BfIRValue ifaceMethodExtVar;
  6178. if ((!ifaceMethodExtData.IsEmpty()) && (!mIsComptimeModule))
  6179. {
  6180. StringT<512> classVDataName;
  6181. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  6182. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  6183. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  6184. BfIRLinkageType_External, BfIRValue(), classVDataName);
  6185. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  6186. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, ifaceMethodExtData);
  6187. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  6188. }
  6189. for (auto& ifaceInstPair : interfaceMap)
  6190. {
  6191. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  6192. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  6193. if (slotNum >= 0)
  6194. {
  6195. BfIRValue vtablePtr;
  6196. int idx = interfaceEntry->mStartVirtualIdx;
  6197. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  6198. if ((endVirtualIdx > ifaceMethodExtStart) && (ifaceMethodExtVar))
  6199. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  6200. else
  6201. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  6202. int slotVirtIdx = slotNum + vDataOfs;
  6203. if (vData[slotVirtIdx] == voidPtrNull)
  6204. {
  6205. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  6206. }
  6207. else
  6208. {
  6209. if (mCompiler->IsHotCompile())
  6210. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  6211. else
  6212. Fail("Interface slot collision error", typeDef->GetRefNode());
  6213. }
  6214. }
  6215. }
  6216. }
  6217. }
  6218. BfIRValue typeNameConst;
  6219. BfIRValue namespaceConst;
  6220. if (needsTypeNames)
  6221. {
  6222. typeNameConst = GetStringObjectValue(typeDef->mName->mString, !mIsComptimeModule);
  6223. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), !mIsComptimeModule);
  6224. }
  6225. else
  6226. {
  6227. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  6228. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  6229. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  6230. }
  6231. int baseTypeId = 0;
  6232. if (typeInstance->mBaseType != NULL)
  6233. {
  6234. baseTypeId = typeInstance->mBaseType->mTypeId;
  6235. }
  6236. BfTypeOptions* typeOptions = NULL;
  6237. if (typeInstance->mTypeOptionsIdx >= 0)
  6238. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6239. SizedArray<BfIRValue, 16> customAttrs;
  6240. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  6241. BfIRValue castedClassVData;
  6242. if (classVDataVar)
  6243. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  6244. else
  6245. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  6246. bool freflectIncludeTypeData = false;
  6247. bool reflectIncludeAllFields = false;
  6248. bool reflectIncludeAllMethods = false;
  6249. if (TypeIsSubTypeOf(typeInstance, attributeType))
  6250. {
  6251. reflectIncludeAllFields = true;
  6252. reflectIncludeAllMethods = true;
  6253. }
  6254. if (typeInstance->IsTuple())
  6255. {
  6256. // Required to generate tuple name at runtime
  6257. reflectIncludeAllFields = true;
  6258. }
  6259. BfReflectKind reflectKind = BfReflectKind_Type;
  6260. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  6261. {
  6262. BfReflectKind reflectKind = BfReflectKind_None;
  6263. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  6264. if (customAttrs != NULL)
  6265. {
  6266. for (auto& attr : customAttrs->mAttributes)
  6267. {
  6268. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  6269. }
  6270. delete customAttrs;
  6271. }
  6272. return reflectKind;
  6273. };
  6274. reflectKind = GetReflectKind(reflectKind, typeInstance);
  6275. // Fields
  6276. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  6277. BfIRValue emptyValueType = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  6278. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  6279. {
  6280. if (customAttributes == NULL)
  6281. return -1;
  6282. Array<BfCustomAttribute*> reflectAttributes;
  6283. for (auto& attr : customAttributes->mAttributes)
  6284. {
  6285. bool wantAttribute = false;
  6286. if (attr.mType->mCustomAttributes != NULL)
  6287. {
  6288. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  6289. if (usageAttribute != NULL)
  6290. {
  6291. // Check for Flags arg
  6292. if (usageAttribute->mCtorArgs.size() < 2)
  6293. continue;
  6294. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  6295. if (constant == NULL)
  6296. continue;
  6297. if (constant->mTypeCode == BfTypeCode_Boolean)
  6298. continue;
  6299. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  6300. wantAttribute = true;
  6301. }
  6302. }
  6303. if ((wantAttribute) && (attr.mType->mIsReified))
  6304. {
  6305. reflectAttributes.Add(&attr);
  6306. }
  6307. }
  6308. if (reflectAttributes.size() == 0)
  6309. return -1;
  6310. #define PUSH_INT8(val) data.push_back((uint8)val)
  6311. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  6312. #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); }
  6313. SizedArray<uint8, 16> data;
  6314. int customAttrIdx = (int)customAttrs.size();
  6315. data.push_back((uint8)reflectAttributes.size());
  6316. for (auto attr : reflectAttributes)
  6317. {
  6318. // Size prefix
  6319. int sizeIdx = (int)data.size();
  6320. PUSH_INT16(0); // mSize
  6321. PUSH_INT32(attr->mType->mTypeId); // mType
  6322. int ctorIdx = -1;
  6323. int ctorCount = 0;
  6324. attr->mType->mTypeDef->PopulateMemberSets();
  6325. BfMemberSetEntry* entry;
  6326. if (attr->mType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  6327. {
  6328. BfMethodDef* nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6329. while (nextMethodDef != NULL)
  6330. {
  6331. if (nextMethodDef == attr->mCtor)
  6332. ctorIdx = ctorCount;
  6333. nextMethodDef = nextMethodDef->mNextWithSameName;
  6334. ctorCount++;
  6335. }
  6336. }
  6337. BF_ASSERT(ctorIdx != -1);
  6338. if (ctorIdx != -1)
  6339. ctorIdx = (ctorCount - 1) - ctorIdx;
  6340. PUSH_INT16(ctorIdx);
  6341. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  6342. int argIdx = 0;
  6343. for (auto arg : attr->mCtorArgs)
  6344. {
  6345. auto argType = ctorMethodInstance->GetParamType(argIdx);
  6346. EncodeAttributeData(typeInstance, argType, arg, data, ctx.mUsedStringIdMap);
  6347. argIdx++;
  6348. }
  6349. int size = (int)data.size() - sizeIdx;
  6350. *((uint16*)&data[sizeIdx]) = size;
  6351. }
  6352. #undef PUSH_INT8
  6353. #undef PUSH_INT16
  6354. #undef PUSH_INT32
  6355. SizedArray<BfIRValue, 16> dataValues;
  6356. for (uint8 val : data)
  6357. dataValues.push_back(GetConstValue8(val));
  6358. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  6359. auto customAttrConst = mBfIRBuilder->CreateConstAgg_Value(dataArrayType, dataValues);
  6360. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  6361. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  6362. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  6363. customAttrs.push_back(customAttrArrayPtr);
  6364. return customAttrIdx;
  6365. };
  6366. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  6367. SizedArray<int, 16> reflectFieldIndices;
  6368. for (int pass = 0; pass < 2; pass++)
  6369. {
  6370. bool skippedField = false;
  6371. reflectFieldIndices.clear();
  6372. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  6373. {
  6374. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6375. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  6376. if (fieldDef == NULL)
  6377. continue;
  6378. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6379. bool includeField = reflectIncludeAllFields;
  6380. if (fieldInstance->mCustomAttributes != NULL)
  6381. {
  6382. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  6383. {
  6384. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6385. {
  6386. includeField = true;
  6387. }
  6388. else
  6389. {
  6390. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6391. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  6392. }
  6393. }
  6394. }
  6395. if ((fieldReflectKind & BfReflectKind_User) != 0)
  6396. includeField = true;
  6397. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  6398. includeField = true;
  6399. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  6400. includeField = true;
  6401. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  6402. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  6403. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  6404. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  6405. includeField |= forceReflectFields;
  6406. if (!includeField)
  6407. {
  6408. skippedField = true;
  6409. continue;
  6410. }
  6411. reflectFieldIndices.Add(fieldIdx);
  6412. }
  6413. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  6414. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  6415. // possible because we write out a SplatData structure containing just TypeIds in that case
  6416. if (pass == 0)
  6417. {
  6418. if (!typeInstance->IsSplattable())
  6419. break;
  6420. if (!skippedField)
  6421. break;
  6422. if (reflectFieldIndices.size() == 0)
  6423. break;
  6424. }
  6425. }
  6426. SizedArray<BfIRValue, 16> fieldTypes;
  6427. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  6428. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  6429. {
  6430. BfType* payloadType = typeInstance->GetUnionInnerType();
  6431. if (!payloadType->IsValuelessType())
  6432. {
  6433. BfIRValue payloadNameConst = GetStringObjectValue("$payload", !mIsComptimeModule);
  6434. SizedArray<BfIRValue, 8> payloadFieldVals;
  6435. if (is32Bit)
  6436. {
  6437. payloadFieldVals =
  6438. {
  6439. emptyValueType,
  6440. payloadNameConst, // mName
  6441. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6442. GetConstValue(0, intPtrType), // mData
  6443. GetConstValue(0, intPtrType), // mDataHi
  6444. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6445. GetConstValue(-1, intType), // mCustomAttributesIdx
  6446. };
  6447. }
  6448. else
  6449. {
  6450. payloadFieldVals =
  6451. {
  6452. emptyValueType,
  6453. payloadNameConst, // mName
  6454. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6455. GetConstValue(0, intPtrType), // mData
  6456. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6457. GetConstValue(-1, intType), // mCustomAttributesIdx
  6458. };
  6459. }
  6460. FixConstValueParams(reflectFieldDataType->ToTypeInstance(), payloadFieldVals);
  6461. auto payloadFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  6462. fieldTypes.push_back(payloadFieldData);
  6463. }
  6464. BfType* dscrType = typeInstance->GetDiscriminatorType();
  6465. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", !mIsComptimeModule);
  6466. SizedArray<BfIRValue, 8> dscrFieldVals;
  6467. if (is32Bit)
  6468. {
  6469. dscrFieldVals =
  6470. {
  6471. emptyValueType,
  6472. dscrNameConst, // mName
  6473. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6474. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6475. GetConstValue(0, intPtrType), // mDataHi
  6476. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6477. GetConstValue(-1, intType), // mCustomAttributesIdx
  6478. };
  6479. }
  6480. else
  6481. {
  6482. dscrFieldVals =
  6483. {
  6484. emptyValueType,
  6485. dscrNameConst, // mName
  6486. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6487. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6488. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6489. GetConstValue(-1, intType), // mCustomAttributesIdx
  6490. };
  6491. }
  6492. auto dscrFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  6493. fieldTypes.push_back(dscrFieldData);
  6494. }
  6495. for (auto fieldIdx : reflectFieldIndices)
  6496. {
  6497. if (!needsTypeData)
  6498. break;
  6499. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6500. fieldTypes.push_back(CreateFieldData(fieldInstance, _HandleCustomAttrs(fieldInstance->mCustomAttributes)));
  6501. }
  6502. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  6503. BfIRValue fieldDataPtr;
  6504. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  6505. if (fieldTypes.size() == 0)
  6506. {
  6507. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  6508. {
  6509. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  6510. SizedArray<BfIRValue, 3> splatTypes;
  6511. SizedArray<BfIRValue, 3> splatOffsets;
  6512. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  6513. {
  6514. auto checkTypeInstance = checkType->ToTypeInstance();
  6515. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  6516. PopulateType(checkTypeInstance);
  6517. if (checkType->IsStruct())
  6518. {
  6519. int dataEnd = offset;
  6520. if (checkTypeInstance->mBaseType != NULL)
  6521. _CheckSplat(checkTypeInstance->mBaseType, offset);
  6522. if (checkTypeInstance->mIsUnion)
  6523. {
  6524. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  6525. _CheckSplat(unionInnerType, offset);
  6526. }
  6527. else
  6528. {
  6529. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  6530. {
  6531. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  6532. if (fieldInstance->mDataIdx >= 0)
  6533. {
  6534. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  6535. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  6536. }
  6537. }
  6538. }
  6539. if (checkTypeInstance->IsEnum())
  6540. {
  6541. // Add discriminator
  6542. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  6543. if (checkTypeInstance->mPacking > 0)
  6544. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  6545. _CheckSplat(dscrType, dataEnd);
  6546. }
  6547. }
  6548. else if (checkType->IsMethodRef())
  6549. {
  6550. // auto methodRefType = (BfMethodRefType*)checkType;
  6551. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6552. // {
  6553. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6554. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  6555. // else
  6556. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  6557. // }
  6558. }
  6559. else if (!checkType->IsValuelessType())
  6560. {
  6561. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  6562. splatOffsets.Add(GetConstValue(offset, intType));
  6563. }
  6564. };
  6565. _CheckSplat(type, 0);
  6566. while (splatTypes.size() < 3)
  6567. {
  6568. splatTypes.Add(GetConstValue(0, typeIdType));
  6569. splatOffsets.Add(GetConstValue(0, intType));
  6570. }
  6571. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  6572. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  6573. SizedArray<BfIRValue, 8> splatVals =
  6574. {
  6575. emptyValueType,
  6576. splatTypesConst,
  6577. splatOffsetsConst
  6578. };
  6579. auto fieldSplatData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  6580. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  6581. fieldSplatData, typeDataName + ".splats");
  6582. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6583. }
  6584. else
  6585. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  6586. }
  6587. else
  6588. {
  6589. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  6590. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstAgg_Value(fieldDataConstType, fieldTypes);
  6591. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  6592. fieldDataConst, "fields." + typeDataName);
  6593. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6594. }
  6595. /// Methods
  6596. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  6597. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  6598. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  6599. struct _SortedMethodInfo
  6600. {
  6601. BfMethodDef* mMethodDef;
  6602. BfMethodCustomAttributes* mMethodCustomAttributes;
  6603. };
  6604. Array<_SortedMethodInfo> sortedMethodList;
  6605. SizedArray<BfIRValue, 16> methodTypes;
  6606. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  6607. {
  6608. if (!needsTypeData)
  6609. break;
  6610. // Disable const method reflection info for now
  6611. if (mIsComptimeModule)
  6612. break;
  6613. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6614. if (!methodInstanceGroup->IsImplemented())
  6615. continue;
  6616. auto methodDef = typeDef->mMethods[methodIdx];
  6617. if (methodDef->mIsNoReflect)
  6618. continue;
  6619. if (methodDef->mHasComptime)
  6620. continue;
  6621. auto defaultMethod = methodInstanceGroup->mDefault;
  6622. if (defaultMethod == NULL)
  6623. continue;
  6624. if (defaultMethod->mIsUnspecialized)
  6625. continue;
  6626. if (!defaultMethod->mIsReified)
  6627. continue;
  6628. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  6629. continue;
  6630. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  6631. continue;
  6632. if (!defaultMethod->mMethodDef->CanReflect())
  6633. continue;
  6634. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6635. bool includeMethod = reflectIncludeAllMethods;
  6636. if (typeInstance->IsDelegateOrFunction())
  6637. includeMethod = true;
  6638. BfMethodCustomAttributes* methodCustomAttributes = NULL;
  6639. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  6640. {
  6641. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes;
  6642. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  6643. {
  6644. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6645. {
  6646. includeMethod = true;
  6647. }
  6648. else
  6649. {
  6650. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6651. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  6652. }
  6653. }
  6654. }
  6655. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject)))
  6656. continue;
  6657. //
  6658. {
  6659. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  6660. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  6661. {
  6662. BfTypeState typeState;
  6663. typeState.mPrevState = mContext->mCurTypeState;
  6664. typeState.mForceActiveTypeDef = methodDef->mDeclaringType;
  6665. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  6666. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  6667. {
  6668. if (paramDecl->mAttributes != NULL)
  6669. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  6670. }
  6671. }
  6672. }
  6673. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  6674. includeMethod = true;
  6675. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  6676. includeMethod = true;
  6677. if ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend))
  6678. {
  6679. if ((methodReflectKind & BfReflectKind_Constructors) != 0)
  6680. includeMethod = true;
  6681. if ((methodDef->IsDefaultCtor()) && ((methodReflectKind & BfReflectKind_DefaultConstructor) != 0))
  6682. includeMethod = true;
  6683. }
  6684. if ((!includeMethod) && (typeOptions != NULL))
  6685. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  6686. if (!includeMethod)
  6687. continue;
  6688. sortedMethodList.Add({ methodDef, methodCustomAttributes });
  6689. }
  6690. auto _GetMethodKind = [](BfMethodDef* methodDef)
  6691. {
  6692. if (methodDef->mMethodType == BfMethodType_Ctor)
  6693. return 0;
  6694. return 1;
  6695. };
  6696. std::sort(sortedMethodList.begin(), sortedMethodList.end(), [_GetMethodKind](const _SortedMethodInfo& lhs, const _SortedMethodInfo& rhs)
  6697. {
  6698. int lhsKind = _GetMethodKind(lhs.mMethodDef);
  6699. int rhsKind = _GetMethodKind(rhs.mMethodDef);
  6700. if (lhsKind != rhsKind)
  6701. return lhsKind < rhsKind;
  6702. if (lhs.mMethodDef->mName != rhs.mMethodDef->mName)
  6703. return lhs.mMethodDef->mName < rhs.mMethodDef->mName;
  6704. return lhs.mMethodDef->mIdx < rhs.mMethodDef->mIdx;
  6705. });
  6706. for (auto& methodInfo : sortedMethodList)
  6707. {
  6708. auto methodDef = methodInfo.mMethodDef;
  6709. int methodIdx = methodDef->mIdx;
  6710. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6711. auto defaultMethod = methodInstanceGroup->mDefault;
  6712. BfModuleMethodInstance moduleMethodInstance;
  6713. BfIRValue funcVal = voidPtrNull;
  6714. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  6715. (!typeInstance->IsUnspecializedType()) &&
  6716. (methodDef->mMethodType != BfMethodType_Ignore) &&
  6717. (methodDef->mMethodType != BfMethodType_Mixin) &&
  6718. (!methodDef->mIsAbstract) &&
  6719. (methodDef->mGenericParams.size() == 0))
  6720. {
  6721. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6722. if (moduleMethodInstance.mFunc)
  6723. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6724. }
  6725. BfIRValue methodNameConst = GetStringObjectValue(methodDef->GetReflectName(), !mIsComptimeModule);
  6726. BfMethodFlags methodFlags = defaultMethod->GetMethodFlags();
  6727. int customAttrIdx = -1;
  6728. int returnCustomAttrIdx = -1;
  6729. if (methodInfo.mMethodCustomAttributes != NULL)
  6730. {
  6731. customAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mCustomAttributes);
  6732. returnCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mReturnCustomAttributes);
  6733. }
  6734. enum ParamFlags
  6735. {
  6736. ParamFlag_None = 0,
  6737. ParamFlag_Splat = 1,
  6738. ParamFlag_Implicit = 2,
  6739. ParamFlag_AppendIdx = 4,
  6740. ParamFlag_Params = 8
  6741. };
  6742. SizedArray<BfIRValue, 8> paramVals;
  6743. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  6744. {
  6745. String paramName = defaultMethod->GetParamName(paramIdx);
  6746. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  6747. ParamFlags paramFlags = ParamFlag_None;
  6748. if (defaultMethod->GetParamIsSplat(paramIdx))
  6749. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  6750. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  6751. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Implicit | ParamFlag_AppendIdx);
  6752. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_Params)
  6753. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Params);
  6754. BfIRValue paramNameConst = GetStringObjectValue(paramName, !mIsComptimeModule);
  6755. int paramCustomAttrIdx = -1;
  6756. if ((methodInfo.mMethodCustomAttributes != NULL) && (paramIdx < (int)methodInfo.mMethodCustomAttributes->mParamCustomAttributes.mSize))
  6757. paramCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mParamCustomAttributes[paramIdx]);
  6758. SizedArray<BfIRValue, 8> paramDataVals =
  6759. {
  6760. emptyValueType,
  6761. paramNameConst,
  6762. GetConstValue(paramType->mTypeId, typeIdType),
  6763. GetConstValue((int32)paramFlags, shortType),
  6764. GetConstValue(-1, intType), // defaultIdx
  6765. GetConstValue(paramCustomAttrIdx, intType) // customAttrIdx
  6766. };
  6767. auto paramData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  6768. paramVals.Add(paramData);
  6769. }
  6770. BfIRValue paramsVal;
  6771. if (paramVals.size() > 0)
  6772. {
  6773. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  6774. BfIRValue paramDataConst = mBfIRBuilder->CreateConstAgg_Value(paramDataArrayType, paramVals);
  6775. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  6776. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  6777. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  6778. }
  6779. else
  6780. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  6781. int vDataVal = -1;
  6782. if (defaultMethod->mVirtualTableIdx != -1)
  6783. {
  6784. int vDataIdx = -1;
  6785. if (type->IsInterface())
  6786. {
  6787. vDataIdx = defaultMethod->mVirtualTableIdx;
  6788. }
  6789. else
  6790. {
  6791. vDataIdx = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  6792. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  6793. {
  6794. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  6795. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6796. if (extMethodIdx >= 0)
  6797. {
  6798. // Extension?
  6799. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6800. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  6801. }
  6802. else
  6803. {
  6804. // Map this new virtual index back to the original index
  6805. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  6806. }
  6807. }
  6808. else
  6809. {
  6810. vDataIdx += defaultMethod->mVirtualTableIdx;
  6811. }
  6812. }
  6813. if (vDataVal == -1)
  6814. vDataVal = vDataIdx * mSystem->mPtrSize;
  6815. }
  6816. SizedArray<BfIRValue, 8> methodDataVals =
  6817. {
  6818. emptyValueType,
  6819. methodNameConst, // mName
  6820. funcVal, // mFuncPtr
  6821. paramsVal,
  6822. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  6823. GetConstValue((int)paramVals.size(), shortType),
  6824. GetConstValue(methodFlags, intType),
  6825. GetConstValue(methodIdx, intType),
  6826. GetConstValue(vDataVal, intType),
  6827. GetConstValue(customAttrIdx, intType),
  6828. GetConstValue(returnCustomAttrIdx, intType),
  6829. };
  6830. auto methodData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  6831. methodTypes.push_back(methodData);
  6832. }
  6833. BfIRValue methodDataPtr;
  6834. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  6835. if (methodTypes.size() == 0)
  6836. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  6837. else
  6838. {
  6839. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  6840. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methodTypes);
  6841. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6842. methodDataConst, "methods." + typeDataName);
  6843. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  6844. }
  6845. /////
  6846. int interfaceCount = 0;
  6847. BfIRValue interfaceDataPtr;
  6848. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  6849. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  6850. Array<bool> wantsIfaceMethod;
  6851. bool wantsIfaceMethods = false;
  6852. if ((typeInstance->mInterfaces.IsEmpty()) || (!needsTypeData))
  6853. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  6854. else
  6855. {
  6856. SizedArray<BfIRValue, 16> interfaces;
  6857. for (auto& interface : typeInstance->mInterfaces)
  6858. {
  6859. SizedArray<BfIRValue, 8> interfaceDataVals =
  6860. {
  6861. emptyValueType,
  6862. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  6863. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  6864. GetConstValue(interface.mStartVirtualIdx, intType),
  6865. };
  6866. auto interfaceData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  6867. interfaces.push_back(interfaceData);
  6868. if (!mIsComptimeModule)
  6869. {
  6870. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6871. {
  6872. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  6873. if (ifaceMethodGroup->mExplicitlyReflected)
  6874. {
  6875. wantsIfaceMethods = true;
  6876. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  6877. while (tableIdx >= wantsIfaceMethod.size())
  6878. wantsIfaceMethod.Add(false);
  6879. wantsIfaceMethod[tableIdx] = true;
  6880. }
  6881. }
  6882. }
  6883. }
  6884. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  6885. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstAgg_Value(interfaceDataArrayType, interfaces);
  6886. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  6887. interfaceDataConst, "interfaces." + typeDataName);
  6888. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  6889. interfaceCount = (int)interfaces.size();
  6890. }
  6891. BfIRValue interfaceMethodTable;
  6892. int ifaceMethodTableSize = 0;
  6893. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  6894. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  6895. {
  6896. SizedArray<BfIRValue, 16> methods;
  6897. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  6898. {
  6899. BfIRValue funcVal = voidPtrNull;
  6900. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  6901. {
  6902. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  6903. if (!methodEntry.mMethodRef.IsNull())
  6904. {
  6905. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  6906. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  6907. (!methodInstance->mMethodDef->mIsAbstract))
  6908. {
  6909. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  6910. if (moduleMethodInstance.mFunc)
  6911. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6912. }
  6913. }
  6914. }
  6915. methods.Add(funcVal);
  6916. }
  6917. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  6918. methods.pop_back();
  6919. if (!methods.IsEmpty())
  6920. {
  6921. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  6922. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methods);
  6923. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6924. methodDataConst, "imethods." + typeDataName);
  6925. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  6926. ifaceMethodTableSize = (int)methods.size();
  6927. }
  6928. }
  6929. if (!interfaceMethodTable)
  6930. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6931. /////
  6932. int underlyingType = 0;
  6933. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  6934. {
  6935. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  6936. }
  6937. int outerTypeId = 0;
  6938. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  6939. if (outerType != NULL)
  6940. {
  6941. outerTypeId = outerType->mTypeId;
  6942. }
  6943. //
  6944. BfIRValue customAttrDataPtr;
  6945. if (customAttrs.size() > 0)
  6946. {
  6947. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  6948. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstAgg_Value(customAttrsArrayType, customAttrs);
  6949. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  6950. customAttrsConst, "customAttrs." + typeDataName);
  6951. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  6952. }
  6953. else
  6954. {
  6955. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6956. }
  6957. SizedArray<BfIRValue, 32> typeDataVals =
  6958. {
  6959. typeData,
  6960. castedClassVData, // mTypeClassVData
  6961. typeNameConst, // mName
  6962. namespaceConst, // mNamespace
  6963. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  6964. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  6965. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  6966. GetConstValue(baseTypeId, typeIdType), // mBaseType
  6967. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  6968. GetConstValue(outerTypeId, typeIdType), // mOuterType
  6969. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  6970. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  6971. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  6972. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  6973. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  6974. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  6975. GetConstValue(0, shortType), // mPropertyDataCount
  6976. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  6977. interfaceDataPtr, // mInterfaceDataPtr
  6978. interfaceMethodTable, // mInterfaceMethodTable
  6979. methodDataPtr, // mMethodDataPtr
  6980. voidPtrNull, // mPropertyDataPtr
  6981. fieldDataPtr, // mFieldDataPtr
  6982. customAttrDataPtr, // mCustomAttrDataPtr
  6983. };
  6984. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  6985. FixConstValueParams(typeInstanceType->ToTypeInstance(), typeDataVals);
  6986. auto typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, typeDataVals);
  6987. if (!needsTypeData)
  6988. {
  6989. // No need for anything beyond typeInstanceData
  6990. }
  6991. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  6992. {
  6993. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6994. SizedArray<BfIRValue, 4> unspecializedData =
  6995. {
  6996. typeInstanceData,
  6997. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  6998. };
  6999. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  7000. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  7001. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, unspecializedData);
  7002. }
  7003. else if (typeInstance->IsGenericTypeInstance())
  7004. {
  7005. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  7006. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  7007. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef->GetDefinition());
  7008. SizedArray<BfIRValue, 4> resolvedTypes;
  7009. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  7010. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  7011. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  7012. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  7013. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  7014. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstAgg_Value(genericArrayType, resolvedTypes);
  7015. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  7016. resolvedTypesConst, "resolvedTypes." + typeDataName);
  7017. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  7018. SizedArray<BfIRValue, 3> specGenericData =
  7019. {
  7020. typeInstanceData,
  7021. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  7022. resovledTypesPtr, // mFieldDataPtr
  7023. };
  7024. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  7025. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, specGenericData);
  7026. if (typeInstance->IsArray())
  7027. {
  7028. auto arrayType = (BfArrayType*)typeInstance;
  7029. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  7030. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  7031. SizedArray<BfIRValue, 4> arrayData =
  7032. {
  7033. typeInstanceData,
  7034. GetConstValue(elementType->mSize, intType), // mElementSize
  7035. GetConstValue(1, byteType), // mRank
  7036. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  7037. };
  7038. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  7039. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  7040. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, arrayData);
  7041. }
  7042. }
  7043. BfIRValue typeDataVar;
  7044. if (needsTypeData)
  7045. {
  7046. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  7047. BfIRLinkageType_External, typeInstanceData, typeDataName);
  7048. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  7049. if (mBfIRBuilder->DbgHasInfo())
  7050. {
  7051. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  7052. }
  7053. }
  7054. else
  7055. {
  7056. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  7057. }
  7058. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  7059. mTypeDataRefs[typeInstance] = typeDataVar;
  7060. if ((!mIsComptimeModule) && (classVDataVar))
  7061. {
  7062. BF_ASSERT(!classVDataName.IsEmpty());
  7063. //vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  7064. int unboxedTypeId = type->mTypeId;
  7065. if (type->IsBoxed())
  7066. unboxedTypeId = type->GetUnderlyingType()->mTypeId;
  7067. if (mSystem->mPtrSize == 4)
  7068. {
  7069. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(type->mTypeId, intPtrType), voidPtrIRType);
  7070. vData[1] = mBfIRBuilder->CreateIntToPtr(GetConstValue(unboxedTypeId, intPtrType), voidPtrIRType);
  7071. }
  7072. else
  7073. {
  7074. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(((int64)unboxedTypeId << 32) | type->mTypeId, intPtrType), voidPtrIRType);
  7075. }
  7076. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  7077. auto classVDataConstData = mBfIRBuilder->CreateConstAgg_Value(classVDataConstDataType, vData);
  7078. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  7079. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7080. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  7081. else
  7082. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  7083. if (mBfIRBuilder->DbgHasInfo())
  7084. {
  7085. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  7086. BfType* voidPtrType = CreatePointerType(voidType);
  7087. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  7088. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  7089. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  7090. }
  7091. }
  7092. return typeDataVar;
  7093. }
  7094. BfIRValue BfModule::FixClassVData(BfIRValue value)
  7095. {
  7096. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  7097. return value;
  7098. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  7099. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  7100. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  7101. }
  7102. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  7103. {
  7104. // Note: this is not just for perf, it fixes a field var-type resolution issue
  7105. if (mBfIRBuilder->mIgnoreWrites)
  7106. return;
  7107. if (mIsComptimeModule)
  7108. return;
  7109. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7110. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  7111. // When we access classes with static constructors FROM a static constructor,
  7112. // we call that other class's static constructor first. Recursion cannot occur, since
  7113. // we simply ignore subsequent attempts to re-enter the constructor
  7114. if (!typeInstance->mHasStaticInitMethod)
  7115. return;
  7116. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  7117. return;
  7118. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  7119. return;
  7120. auto checkTypeDef = typeInstance->mTypeDef;
  7121. checkTypeDef->PopulateMemberSets();
  7122. BfMethodDef* nextMethodDef = NULL;
  7123. BfMemberSetEntry* entry;
  7124. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  7125. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  7126. while (nextMethodDef != NULL)
  7127. {
  7128. auto checkMethod = nextMethodDef;
  7129. nextMethodDef = nextMethodDef->mNextWithSameName;
  7130. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  7131. if (methodModule)
  7132. {
  7133. auto methodInstance = methodModule.mMethodInstance;
  7134. if ((methodInstance != NULL) &&
  7135. (methodInstance->mMethodDef->mIsStatic) &&
  7136. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  7137. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  7138. {
  7139. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  7140. break;
  7141. }
  7142. }
  7143. }
  7144. }
  7145. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  7146. {
  7147. if (!methodInstance->mIsIntrinsic)
  7148. return BfIRFunction();
  7149. auto methodOwner = methodInstance->GetOwner();
  7150. auto methodDef = methodInstance->mMethodDef;
  7151. auto methodDeclaration = methodDef->GetMethodDeclaration();
  7152. if (!methodDef->mIsExtern)
  7153. return BfIRFunction();
  7154. if (methodInstance->GetCustomAttributes() == NULL)
  7155. return BfIRFunction();
  7156. auto customAttribute = methodInstance->GetCustomAttributes()->Get(mCompiler->mIntrinsicAttributeTypeDef);
  7157. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute->mCtorArgs[0]);
  7158. String error;
  7159. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  7160. {
  7161. int stringId = constant->mInt32;
  7162. auto entry = mContext->mStringObjectIdMap[stringId];
  7163. String intrinName = entry.mString;
  7164. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  7165. if (intrinId != -1)
  7166. {
  7167. if (intrinId == BfIRIntrinsic_Malloc)
  7168. {
  7169. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  7170. }
  7171. else if (intrinId == BfIRIntrinsic_Free)
  7172. {
  7173. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  7174. }
  7175. SizedArray<BfIRType, 2> paramTypes;
  7176. for (auto& param : methodInstance->mParams)
  7177. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  7178. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  7179. }
  7180. else if (reportFailure)
  7181. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  7182. }
  7183. else if (reportFailure)
  7184. error = "Intrinsic name must be a constant string";
  7185. if (reportFailure)
  7186. {
  7187. Fail(error, customAttribute->mRef);
  7188. }
  7189. return BfIRFunction();
  7190. }
  7191. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  7192. {
  7193. if (mBfIRBuilder->mIgnoreWrites)
  7194. return mBfIRBuilder->GetFakeFunction();
  7195. if (!mBuiltInFuncs[(int)funcTypeId])
  7196. {
  7197. SizedArray<BfIRType, 4> paramTypes;
  7198. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  7199. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  7200. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  7201. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  7202. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  7203. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  7204. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  7205. BfIRFunctionType funcType;
  7206. BfIRFunction func;
  7207. switch (funcTypeId)
  7208. {
  7209. case BfBuiltInFuncType_PrintF:
  7210. paramTypes.Add(nullPtrType);
  7211. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  7212. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  7213. break;
  7214. case BfBuiltInFuncType_Malloc:
  7215. {
  7216. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7217. {
  7218. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  7219. }
  7220. else
  7221. {
  7222. String funcName = mCompiler->mOptions.mMallocLinkName;
  7223. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  7224. funcName = "malloc";
  7225. func = mBfIRBuilder->GetFunction(funcName);
  7226. if (!func)
  7227. {
  7228. paramTypes.clear();
  7229. paramTypes.push_back(intType);
  7230. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  7231. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  7232. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  7233. }
  7234. }
  7235. }
  7236. break;
  7237. case BfBuiltInFuncType_Free:
  7238. {
  7239. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7240. {
  7241. func = GetInternalMethod("Dbg_RawFree").mFunc;
  7242. }
  7243. else
  7244. {
  7245. String funcName = mCompiler->mOptions.mFreeLinkName;
  7246. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  7247. funcName = "free";
  7248. func = mBfIRBuilder->GetFunction(funcName);
  7249. if (!func)
  7250. {
  7251. paramTypes.clear();
  7252. paramTypes.push_back(nullPtrType);
  7253. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  7254. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  7255. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  7256. }
  7257. }
  7258. }
  7259. break;
  7260. case BfBuiltInFuncType_LoadSharedLibraries:
  7261. paramTypes.clear();
  7262. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  7263. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  7264. break;
  7265. default: break;
  7266. }
  7267. mBuiltInFuncs[(int)funcTypeId] = func;
  7268. return func;
  7269. }
  7270. return mBuiltInFuncs[(int)funcTypeId];
  7271. }
  7272. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized, Array<BfTypeReference*>* deferredResolveTypes)
  7273. {
  7274. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  7275. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  7276. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  7277. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  7278. BfAutoComplete* bfAutocomplete = NULL;
  7279. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  7280. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  7281. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  7282. {
  7283. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  7284. {
  7285. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  7286. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  7287. {
  7288. String filter = nameNode->ToString();
  7289. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  7290. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  7291. if (nameIdx != 0)
  7292. {
  7293. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  7294. }
  7295. }
  7296. }
  7297. }
  7298. for (auto constraint : constraintDef->mConstraints)
  7299. {
  7300. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  7301. {
  7302. BfGenericOperatorConstraintInstance opConstraintInstance;
  7303. if (opConstraint->mLeftType != NULL)
  7304. {
  7305. if (bfAutocomplete != NULL)
  7306. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  7307. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces_All);
  7308. if (opConstraintInstance.mLeftType == NULL)
  7309. continue;
  7310. }
  7311. if (opConstraint->mRightType == NULL)
  7312. {
  7313. // We had a failure in parsing
  7314. continue;
  7315. }
  7316. if (opConstraint->mRightType != NULL)
  7317. {
  7318. if (bfAutocomplete != NULL)
  7319. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  7320. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces_All);
  7321. if (opConstraintInstance.mRightType == NULL)
  7322. continue;
  7323. }
  7324. if (opConstraint->mOpToken == NULL)
  7325. {
  7326. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  7327. continue;
  7328. }
  7329. if (opConstraint->mLeftType != NULL)
  7330. {
  7331. if (opConstraint->mRightType == NULL)
  7332. {
  7333. // Parse should have failed
  7334. continue;
  7335. }
  7336. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  7337. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  7338. {
  7339. Fail("Invalid binary operator", opConstraint->mOpToken);
  7340. continue;
  7341. }
  7342. }
  7343. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  7344. {
  7345. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  7346. }
  7347. else
  7348. {
  7349. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  7350. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  7351. {
  7352. Fail("Invalid unary operator", opConstraint->mOpToken);
  7353. continue;
  7354. }
  7355. }
  7356. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  7357. continue;
  7358. }
  7359. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  7360. if (bfAutocomplete != NULL)
  7361. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  7362. //TODO: Constraints may refer to other generic params (of either type or method)
  7363. // TO allow resolution, perhaps move this generic param initialization into GetMethodInstance (passing a genericPass bool)
  7364. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_AllowGenericMethodParamConstValue;
  7365. if (isUnspecialized)
  7366. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_DisallowComptime);
  7367. // We we have a deferredResolveTypes then we defer the generic validation, because we may have a case like
  7368. // `where T : Dictionay<TElem, int> and TElem : IHashable` and we don't want to throw the error on `T` before we build `TElem`
  7369. BfType* constraintType;
  7370. if (constraintTypeRef->IsA<BfVarTypeReference>())
  7371. constraintType = GetPrimitiveType(BfTypeCode_Var);
  7372. else
  7373. constraintType = ResolveTypeRef(constraintTypeRef, (deferredResolveTypes != NULL) ? BfPopulateType_Identity : BfPopulateType_Declaration, resolveFlags);
  7374. if (constraintType != NULL)
  7375. {
  7376. if (deferredResolveTypes != NULL)
  7377. {
  7378. PopulateType(constraintType, BfPopulateType_Declaration);
  7379. if (constraintType->IsUnspecializedTypeVariation())
  7380. deferredResolveTypes->Add(constraintTypeRef);
  7381. }
  7382. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7383. {
  7384. bool isValidTypeCode = false;
  7385. BfTypeCode typeCode = BfTypeCode_None;
  7386. if (constraintType->IsTypedPrimitive())
  7387. {
  7388. auto underlyingType = constraintType->GetUnderlyingType();
  7389. if (underlyingType->IsPrimitiveType())
  7390. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  7391. }
  7392. if (constraintType->IsPrimitiveType())
  7393. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  7394. if (constraintType->IsInstanceOf(mCompiler->mStringTypeDef))
  7395. isValidTypeCode = true;
  7396. if (constraintType->IsValueType())
  7397. isValidTypeCode = true;
  7398. if (constraintType->IsVar())
  7399. isValidTypeCode = true;
  7400. switch (typeCode)
  7401. {
  7402. case BfTypeCode_StringId:
  7403. case BfTypeCode_Boolean:
  7404. case BfTypeCode_Int8:
  7405. case BfTypeCode_UInt8:
  7406. case BfTypeCode_Int16:
  7407. case BfTypeCode_UInt16:
  7408. case BfTypeCode_Int32:
  7409. case BfTypeCode_UInt32:
  7410. case BfTypeCode_Int64:
  7411. case BfTypeCode_UInt64:
  7412. case BfTypeCode_IntPtr:
  7413. case BfTypeCode_UIntPtr:
  7414. case BfTypeCode_IntUnknown:
  7415. case BfTypeCode_UIntUnknown:
  7416. case BfTypeCode_Float:
  7417. case BfTypeCode_Double:
  7418. case BfTypeCode_Char8:
  7419. case BfTypeCode_Char16:
  7420. case BfTypeCode_Char32:
  7421. isValidTypeCode = true;
  7422. break;
  7423. default: break;
  7424. }
  7425. if (isValidTypeCode)
  7426. {
  7427. genericParamInstance->mTypeConstraint = constraintType;
  7428. }
  7429. else
  7430. {
  7431. Fail("Const constraint must be a valuetype or string", constraintTypeRef);
  7432. }
  7433. }
  7434. else
  7435. {
  7436. bool checkEquality = false;
  7437. if (constraintType->IsVar())
  7438. {
  7439. // From a `comptype` generic undef resolution. Ignore.
  7440. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_ComptypeExpr);
  7441. genericParamInstance->mComptypeConstraint.Add(constraintTypeRef);
  7442. continue;
  7443. }
  7444. else if (constraintType->IsPrimitiveType())
  7445. {
  7446. checkEquality = true;
  7447. }
  7448. if (constraintType->IsArray())
  7449. {
  7450. if (isUnspecialized)
  7451. {
  7452. 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);
  7453. continue;
  7454. }
  7455. checkEquality = true;
  7456. }
  7457. if (constraintType->IsGenericParam())
  7458. {
  7459. checkEquality = true;
  7460. }
  7461. else if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  7462. {
  7463. checkEquality = true;
  7464. }
  7465. if (checkEquality)
  7466. {
  7467. if (genericParamInstance->mTypeConstraint != NULL)
  7468. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  7469. genericParamInstance->mTypeConstraint = constraintType;
  7470. }
  7471. else if (constraintType->IsInterface())
  7472. {
  7473. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  7474. }
  7475. else
  7476. {
  7477. auto constraintTypeInst = constraintType->ToTypeInstance();
  7478. if (genericParamInstance->mTypeConstraint != NULL)
  7479. {
  7480. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  7481. {
  7482. // Allow more specific type
  7483. genericParamInstance->mTypeConstraint = constraintTypeInst;
  7484. }
  7485. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  7486. {
  7487. // Silently ignore less-specific type
  7488. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  7489. {
  7490. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  7491. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Class);
  7492. }
  7493. }
  7494. else
  7495. {
  7496. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  7497. return;
  7498. }
  7499. }
  7500. else
  7501. genericParamInstance->mTypeConstraint = constraintType;
  7502. }
  7503. }
  7504. }
  7505. }
  7506. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  7507. (genericParamInstance->mTypeConstraint == NULL))
  7508. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  7509. }
  7510. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  7511. {
  7512. if (genericParamSource.mMethodInstance != NULL)
  7513. {
  7514. //auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  7515. //SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  7516. return MethodToString(genericParamSource.mMethodInstance);
  7517. }
  7518. else
  7519. {
  7520. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  7521. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  7522. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  7523. return TypeToString(typeInst);
  7524. }
  7525. }
  7526. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  7527. {
  7528. Array<String> methodParamNameOverrides;
  7529. auto _TypeToString = [&](BfType* type)
  7530. {
  7531. if (genericParamSource.mMethodInstance != NULL)
  7532. {
  7533. if (methodParamNameOverrides.IsEmpty())
  7534. {
  7535. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  7536. methodParamNameOverrides.Add(genericParam->mName);
  7537. }
  7538. return TypeToString(type, &methodParamNameOverrides);
  7539. }
  7540. return TypeToString(type);
  7541. };
  7542. bool ignoreErrors = (errorOut == NULL) ||
  7543. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  7544. if (checkArgType->IsVar())
  7545. return true;
  7546. BfType* origCheckArgType = checkArgType;
  7547. if (origCheckArgType->IsRef())
  7548. origCheckArgType = origCheckArgType->GetUnderlyingType();
  7549. bool argIsReferenceType = false;
  7550. int checkGenericParamFlags = 0;
  7551. if (checkArgType->IsGenericParam())
  7552. {
  7553. BfGenericParamInstance* checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType, false, BfFailHandleKind_Soft);
  7554. if (checkGenericParamInst == NULL)
  7555. return false;
  7556. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  7557. if (checkGenericParamInst->mTypeConstraint != NULL)
  7558. checkArgType = checkGenericParamInst->mTypeConstraint;
  7559. if (checkGenericParamInst->mGenericParamFlags & BfGenericParamFlag_Var)
  7560. checkArgType = GetPrimitiveType(BfTypeCode_Var);
  7561. // if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  7562. // {
  7563. // argMayBeReferenceType = false;
  7564. // }
  7565. // else
  7566. // {
  7567. // argMayBeReferenceType = true;
  7568. // }
  7569. }
  7570. if (checkArgType->IsObjectOrInterface())
  7571. argIsReferenceType = true;
  7572. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mMethodInfoEx != NULL))
  7573. {
  7574. for (int genericParamIdx = (int)mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  7575. genericParamIdx < mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  7576. {
  7577. auto genericParamInst = mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  7578. if ((genericParamInst->mExternType == checkArgType) && (checkArgType->IsUnspecializedType()))
  7579. {
  7580. checkGenericParamFlags |= genericParamInst->mGenericParamFlags;
  7581. }
  7582. }
  7583. }
  7584. BfTypeInstance* typeConstraintInst = NULL;
  7585. if (genericParamInst->mTypeConstraint != NULL)
  7586. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  7587. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  7588. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  7589. {
  7590. if ((!ignoreErrors) && (PreFail()))
  7591. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  7592. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7593. return false;
  7594. }
  7595. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  7596. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  7597. {
  7598. if ((!ignoreErrors) && (PreFail()))
  7599. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  7600. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7601. return false;
  7602. }
  7603. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  7604. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argIsReferenceType))
  7605. {
  7606. if ((!ignoreErrors) && (PreFail()))
  7607. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  7608. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7609. return false;
  7610. }
  7611. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum)
  7612. {
  7613. bool isEnum = checkArgType->IsEnum();
  7614. if ((origCheckArgType->IsGenericParam()) && (checkArgType->IsInstanceOf(mCompiler->mEnumTypeDef)))
  7615. isEnum = true;
  7616. if (((checkGenericParamFlags & (BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!isEnum))
  7617. {
  7618. if ((!ignoreErrors) && (PreFail()))
  7619. *errorOut = Fail(StrFormat("The type '%s' must be an enum type in order to use it as parameter '%s' for '%s'",
  7620. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7621. return false;
  7622. }
  7623. }
  7624. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) &&
  7625. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (checkArgType->IsInterface()))
  7626. {
  7627. if ((!ignoreErrors) && (PreFail()))
  7628. *errorOut = Fail(StrFormat("The type '%s' must be an concrete type in order to use it as parameter '%s' for '%s'",
  7629. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7630. return false;
  7631. }
  7632. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Interface) &&
  7633. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsInterface()))
  7634. {
  7635. if ((!ignoreErrors) && (PreFail()))
  7636. *errorOut = Fail(StrFormat("The type '%s' must be an interface type in order to use it as parameter '%s' for '%s'",
  7637. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7638. return false;
  7639. }
  7640. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7641. {
  7642. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  7643. {
  7644. if ((!ignoreErrors) && (PreFail()))
  7645. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  7646. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7647. return false;
  7648. }
  7649. }
  7650. else
  7651. {
  7652. if (checkArgType->IsConstExprValue())
  7653. {
  7654. if ((!ignoreErrors) && (PreFail()))
  7655. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  7656. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7657. return false;
  7658. }
  7659. }
  7660. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  7661. {
  7662. bool canDelete = false;
  7663. if (checkArgType->IsPointer())
  7664. canDelete = true;
  7665. else if (checkArgType->IsObjectOrInterface())
  7666. canDelete = true;
  7667. else if ((checkGenericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var)) != 0)
  7668. canDelete = true;
  7669. if (!canDelete)
  7670. {
  7671. if ((!ignoreErrors) && (PreFail()))
  7672. {
  7673. if (checkArgType->IsGenericParam())
  7674. *errorOut = Fail(StrFormat("Must add 'where %s : delete' constraint in order to use type as parameter '%s' for '%s'",
  7675. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7676. else
  7677. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  7678. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7679. }
  7680. return false;
  7681. }
  7682. }
  7683. auto checkArgElementType = checkArgType;
  7684. if (checkArgElementType->IsPointer())
  7685. {
  7686. auto ptrType = (BfPointerType*)checkArgElementType;
  7687. checkArgElementType = ptrType->mElementType;
  7688. }
  7689. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  7690. {
  7691. bool canAlloc = false;
  7692. if (auto checkTypeInst = checkArgElementType->ToTypeInstance())
  7693. {
  7694. if (checkTypeInst->IsObjectOrStruct())
  7695. {
  7696. checkTypeInst->mTypeDef->PopulateMemberSets();
  7697. BfMemberSetEntry* entry = NULL;
  7698. BfMethodDef* checkMethodDef = NULL;
  7699. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  7700. if (entry != NULL)
  7701. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  7702. bool hadProtected = false;
  7703. while (checkMethodDef != NULL)
  7704. {
  7705. if (!checkMethodDef->mParams.IsEmpty())
  7706. {
  7707. auto firstParam = checkMethodDef->mParams[0];
  7708. if (((firstParam->mParamKind == BfParamKind_Params) || (firstParam->mParamKind == BfParamKind_AppendIdx) || (firstParam->mParamKind == BfParamKind_VarArgs)) ||
  7709. ((firstParam->mParamDeclaration != NULL) && (firstParam->mParamDeclaration->mInitializer != NULL)))
  7710. {
  7711. // Allow all-default params
  7712. }
  7713. else
  7714. {
  7715. checkMethodDef = checkMethodDef->mNextWithSameName;
  7716. continue;
  7717. }
  7718. }
  7719. if (checkMethodDef->mProtection == BfProtection_Public)
  7720. {
  7721. canAlloc = true;
  7722. break;
  7723. }
  7724. if ((checkMethodDef->mProtection == BfProtection_Protected) || (checkMethodDef->mProtection == BfProtection_ProtectedInternal))
  7725. hadProtected = true;
  7726. checkMethodDef = checkMethodDef->mNextWithSameName;
  7727. }
  7728. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  7729. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  7730. }
  7731. }
  7732. else if (checkArgElementType->IsGenericParam())
  7733. {
  7734. canAlloc = (checkGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) != 0;
  7735. }
  7736. else if (checkArgElementType->IsPrimitiveType())
  7737. {
  7738. // Any primitive types and stuff can be allocated
  7739. canAlloc = true;
  7740. }
  7741. if (!canAlloc)
  7742. {
  7743. if ((!ignoreErrors) && (PreFail()))
  7744. {
  7745. if (checkArgType->IsGenericParam())
  7746. *errorOut = Fail(StrFormat("Must add 'where %s : new' constraint in order to use type as parameter '%s' for '%s'",
  7747. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7748. else
  7749. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  7750. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7751. }
  7752. return false;
  7753. }
  7754. }
  7755. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  7756. return true;
  7757. if (genericParamInst->mTypeConstraint != NULL)
  7758. {
  7759. bool constraintMatched = false;
  7760. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7761. {
  7762. if (checkArgType->IsConstExprValue())
  7763. {
  7764. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  7765. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  7766. {
  7767. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  7768. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  7769. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  7770. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  7771. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  7772. (primType->mTypeDef->mTypeCode != BfTypeCode_Let) &&
  7773. (primType->mTypeDef->mTypeCode != BfTypeCode_Var))
  7774. {
  7775. bool doError = true;
  7776. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  7777. {
  7778. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7779. {
  7780. if (mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue))
  7781. doError = false;
  7782. }
  7783. }
  7784. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_Float) && ((constExprValueType->mValue.mTypeCode == BfTypeCode_Double)))
  7785. {
  7786. doError = false;
  7787. }
  7788. if (doError)
  7789. {
  7790. if ((!ignoreErrors) && (PreFail()))
  7791. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7792. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7793. return false;
  7794. }
  7795. }
  7796. }
  7797. else if (genericParamInst->mTypeConstraint != constExprValueType->mType)
  7798. {
  7799. if ((!ignoreErrors) && (PreFail()))
  7800. *errorOut = Fail(StrFormat("Const generic argument '%s', declared as '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7801. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7802. return false;
  7803. }
  7804. }
  7805. }
  7806. else
  7807. {
  7808. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  7809. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  7810. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7811. if (convCheckConstraint == NULL)
  7812. return false;
  7813. if ((checkArgType->IsMethodRef()) || (checkArgType->IsFunction()))
  7814. {
  7815. if (convCheckConstraint->IsDelegate())
  7816. {
  7817. BfMethodInstance* checkMethodInstance;
  7818. if (checkArgType->IsMethodRef())
  7819. {
  7820. auto methodRefType = (BfMethodRefType*)checkArgType;
  7821. checkMethodInstance = methodRefType->mMethodRef;
  7822. }
  7823. else
  7824. {
  7825. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  7826. }
  7827. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  7828. if (checkMethodInstance->HasExplicitThis() != 0)
  7829. {
  7830. // Don't allow functions with explicit 'this'
  7831. }
  7832. else
  7833. {
  7834. BfExprEvaluator exprEvaluator(this);
  7835. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  7836. constraintMatched = true;
  7837. }
  7838. }
  7839. else if (convCheckConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef))
  7840. constraintMatched = true;
  7841. else if ((checkArgType->IsFunction()) && (convCheckConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))
  7842. constraintMatched = true;
  7843. }
  7844. else if ((checkArgType == convCheckConstraint) || (checkArgType->IsVar()) || (TypeIsSubTypeOf(checkArgType->ToTypeInstance(), convCheckConstraint->ToTypeInstance())))
  7845. {
  7846. constraintMatched = true;
  7847. }
  7848. else if (origCheckArgType->IsWrappableType())
  7849. {
  7850. if (origCheckArgType->IsSizedArray())
  7851. {
  7852. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  7853. if (convCheckConstraint->IsGenericTypeInstance())
  7854. {
  7855. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  7856. if (convCheckConstraintInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  7857. {
  7858. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  7859. {
  7860. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  7861. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  7862. constraintMatched = true;
  7863. }
  7864. }
  7865. }
  7866. }
  7867. if (!constraintMatched)
  7868. {
  7869. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7870. if ((wrappedStructType == convCheckConstraint) || (TypeIsSubTypeOf(wrappedStructType, convCheckConstraint->ToTypeInstance())))
  7871. constraintMatched = true;
  7872. }
  7873. }
  7874. if (!constraintMatched)
  7875. {
  7876. if ((!ignoreErrors) && (PreFail()))
  7877. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  7878. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  7879. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  7880. return false;
  7881. }
  7882. }
  7883. }
  7884. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  7885. {
  7886. BfType* convCheckConstraint = checkConstraint;
  7887. if (convCheckConstraint->IsUnspecializedType())
  7888. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7889. if (convCheckConstraint == NULL)
  7890. return false;
  7891. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  7892. bool implementsInterface = false;
  7893. if (origCheckArgType != checkArgType)
  7894. {
  7895. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  7896. }
  7897. if (!implementsInterface)
  7898. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  7899. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  7900. {
  7901. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7902. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7903. implementsInterface = true;
  7904. }
  7905. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  7906. {
  7907. auto underlyingType = origCheckArgType->GetUnderlyingType();
  7908. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  7909. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7910. implementsInterface = true;
  7911. }
  7912. if (!implementsInterface)
  7913. {
  7914. if ((!ignoreErrors) && (PreFail()))
  7915. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  7916. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  7917. return false;
  7918. }
  7919. }
  7920. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  7921. {
  7922. auto leftType = checkOpConstraint.mLeftType;
  7923. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  7924. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs, mCurTypeInstance);
  7925. if (leftType != NULL)
  7926. leftType = FixIntUnknown(leftType);
  7927. auto rightType = checkOpConstraint.mRightType;
  7928. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  7929. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs, mCurTypeInstance);
  7930. if (rightType != NULL)
  7931. rightType = FixIntUnknown(rightType);
  7932. BfConstraintState constraintSet;
  7933. constraintSet.mPrevState = mContext->mCurConstraintState;
  7934. constraintSet.mGenericParamInstance = genericParamInst;
  7935. constraintSet.mLeftType = leftType;
  7936. constraintSet.mRightType = rightType;
  7937. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  7938. if (!CheckConstraintState(NULL))
  7939. return false;
  7940. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  7941. {
  7942. BfExprEvaluator exprEvaluator(this);
  7943. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  7944. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7945. //
  7946. {
  7947. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7948. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7949. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  7950. }
  7951. if ((!exprEvaluator.mResult) ||
  7952. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  7953. {
  7954. if ((!ignoreErrors) && (PreFail()))
  7955. {
  7956. if (genericParamInst->mExternType != NULL)
  7957. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  7958. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  7959. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7960. ), checkArgTypeRef);
  7961. else
  7962. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  7963. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7964. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7965. ), checkArgTypeRef);
  7966. }
  7967. return false;
  7968. }
  7969. }
  7970. else
  7971. {
  7972. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7973. StringT<128> failedOpName;
  7974. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  7975. {
  7976. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7977. failedOpName = "implicit conversion from '";
  7978. }
  7979. else
  7980. {
  7981. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7982. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7983. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  7984. {
  7985. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7986. failedOpName = "explicit conversion from '";
  7987. }
  7988. else
  7989. {
  7990. BfExprEvaluator exprEvaluator(this);
  7991. exprEvaluator.mResult = rightValue;
  7992. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  7993. if ((!exprEvaluator.mResult) ||
  7994. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  7995. {
  7996. failedOpName += "unary operation '";
  7997. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  7998. }
  7999. }
  8000. }
  8001. if (!failedOpName.IsEmpty())
  8002. {
  8003. if ((!ignoreErrors) && (PreFail()))
  8004. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  8005. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  8006. failedOpName.c_str(), TypeToString(rightType).c_str()
  8007. ), checkArgTypeRef);
  8008. return false;
  8009. }
  8010. }
  8011. }
  8012. return true;
  8013. }
  8014. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  8015. {
  8016. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  8017. {
  8018. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  8019. return genericParamType;
  8020. }
  8021. auto genericParamType = new BfGenericParamType();
  8022. genericParamType->mContext = mContext;
  8023. genericParamType->mGenericParamKind = paramKind;
  8024. genericParamType->mGenericParamIdx = paramIdx;
  8025. PopulateType(genericParamType);
  8026. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  8027. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  8028. BfResolvedTypeSet::LookupContext lookupCtx;
  8029. lookupCtx.mModule = this;
  8030. BfResolvedTypeSet::EntryRef typeEntry;
  8031. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  8032. BF_ASSERT(inserted);
  8033. typeEntry->mValue = genericParamType;
  8034. return genericParamType;
  8035. }
  8036. static int sValueFromExprIdx = 0;
  8037. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  8038. {
  8039. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  8040. if ((result) && (!result.mType->IsVar()) && (!ignoreNullable))
  8041. {
  8042. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  8043. //TODO: Make this work, needed for 'void' and such
  8044. BfType* nullableType = NULL;
  8045. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  8046. {
  8047. BfTypeVector typeVec;
  8048. typeVec.push_back(result.mType);
  8049. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  8050. BF_ASSERT(nullableType != NULL);
  8051. }
  8052. // Go back to start and do any setup we need
  8053. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  8054. BfTypedValue nullableTypedValue;
  8055. if (nullableType != NULL)
  8056. {
  8057. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  8058. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  8059. GetConstValue(nullableType->mSize), nullableType->mAlign);
  8060. }
  8061. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  8062. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  8063. mBfIRBuilder->SetInsertPoint(notNullBB);
  8064. result = LoadValue(result);
  8065. if (nullableTypedValue)
  8066. {
  8067. auto elementType = nullableType->GetUnderlyingType();
  8068. if (elementType->IsVar())
  8069. {
  8070. // Do nothing
  8071. }
  8072. else if (elementType->IsValuelessType())
  8073. {
  8074. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  8075. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  8076. }
  8077. else
  8078. {
  8079. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  8080. mBfIRBuilder->CreateAlignedStore(result.mValue, ptrValue, result.mType->mAlign);
  8081. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  8082. mBfIRBuilder->CreateAlignedStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue, 1);
  8083. }
  8084. result = nullableTypedValue;
  8085. }
  8086. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  8087. AddBasicBlock(pendingNullCond->mDoneBB);
  8088. if (nullableType == NULL)
  8089. {
  8090. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  8091. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  8092. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  8093. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  8094. {
  8095. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  8096. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  8097. }
  8098. result.mValue = phi;
  8099. }
  8100. }
  8101. else
  8102. {
  8103. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  8104. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  8105. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  8106. AddBasicBlock(pendingNullCond->mDoneBB);
  8107. }
  8108. delete mCurMethodState->mPendingNullConditional;
  8109. mCurMethodState->mPendingNullConditional = NULL;
  8110. return result;
  8111. }
  8112. BF_NOINLINE void BfModule::EvaluateWithNewConditionalScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  8113. {
  8114. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  8115. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData);
  8116. if (mCurMethodState != NULL)
  8117. {
  8118. deferredLocalAssignData.mIsIfCondition = true;
  8119. deferredLocalAssignData.mIfMayBeSkipped = true;
  8120. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  8121. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  8122. mCurMethodState->mDeferredLocalAssignData = &deferredLocalAssignData;
  8123. }
  8124. BfScopeData newScope;
  8125. newScope.mOuterIsConditional = true;
  8126. newScope.mAllowTargeting = false;
  8127. if (mCurMethodState != NULL)
  8128. {
  8129. mCurMethodState->AddScope(&newScope);
  8130. NewScopeState(true, false);
  8131. }
  8132. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  8133. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  8134. if (mCurMethodState != NULL)
  8135. RestoreScopeState();
  8136. }
  8137. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  8138. {
  8139. //
  8140. {
  8141. BP_ZONE("CreateValueFromExpression:CheckStack");
  8142. StackHelper stackHelper;
  8143. if (!stackHelper.CanStackExpand(128 * 1024))
  8144. {
  8145. BfTypedValue result;
  8146. if (!stackHelper.Execute([&]()
  8147. {
  8148. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  8149. }))
  8150. {
  8151. Fail("Expression too complex to compile", expr);
  8152. }
  8153. return result;
  8154. }
  8155. }
  8156. BP_ZONE("BfModule::CreateValueFromExpression");
  8157. if (outOrigType != NULL)
  8158. *outOrigType = NULL;
  8159. exprEvaluator.mExpectingType = wantTypeRef;
  8160. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  8161. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  8162. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  8163. {
  8164. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope->mScopeKind != BfScopeKind_StatementTarget_Conditional))
  8165. {
  8166. EvaluateWithNewConditionalScope(exprEvaluator, expr, flags);
  8167. }
  8168. else
  8169. {
  8170. SetAndRestoreValue<bool> prevIsConditional(mCurMethodState->mCurScope->mIsConditional, true);
  8171. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  8172. }
  8173. }
  8174. else
  8175. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  8176. if (!exprEvaluator.mResult)
  8177. {
  8178. if ((flags & BfEvalExprFlags_InferReturnType) != 0)
  8179. return exprEvaluator.mResult;
  8180. if (!mCompiler->mPassInstance->HasFailed())
  8181. {
  8182. if (PreFail())
  8183. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  8184. }
  8185. return BfTypedValue();
  8186. }
  8187. auto typedVal = exprEvaluator.mResult;
  8188. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  8189. {
  8190. BF_ASSERT(typedVal.mType->IsGenericParam());
  8191. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  8192. bool handled = false;
  8193. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  8194. {
  8195. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  8196. if (genericTypeConstraint != NULL)
  8197. {
  8198. auto underlyingConstraint = genericTypeConstraint;
  8199. if ((underlyingConstraint != NULL) && (underlyingConstraint->IsBoxed()))
  8200. underlyingConstraint = underlyingConstraint->GetUnderlyingType();
  8201. if (underlyingConstraint != NULL)
  8202. {
  8203. BfTypedValue result;
  8204. result.mKind = BfTypedValueKind_Value;
  8205. result.mType = genericTypeConstraint;
  8206. result.mValue = mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(underlyingConstraint));
  8207. typedVal = result;
  8208. handled = true;
  8209. }
  8210. }
  8211. }
  8212. if (!handled)
  8213. {
  8214. //Fail("Only const generic parameters can be used as values", expr);
  8215. AssertErrorState();
  8216. return BfTypedValue();
  8217. }
  8218. }
  8219. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  8220. FixIntUnknown(typedVal);
  8221. if (!mBfIRBuilder->mIgnoreWrites)
  8222. FixValueActualization(typedVal);
  8223. exprEvaluator.CheckResultForReading(typedVal);
  8224. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  8225. {
  8226. if ((flags & BfEvalExprFlags_NoCast) == 0)
  8227. {
  8228. // Only allow a 'ref' type if we have an explicit 'ref' operator
  8229. bool allowRef = false;
  8230. BfAstNode* checkExpr = expr;
  8231. while (checkExpr != NULL)
  8232. {
  8233. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  8234. checkExpr = parenExpr->mExpression;
  8235. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  8236. {
  8237. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  8238. allowRef = true;
  8239. break;
  8240. }
  8241. if (auto block = BfNodeDynCast<BfBlock>(checkExpr))
  8242. {
  8243. if (block->mChildArr.mSize == 0)
  8244. break;
  8245. checkExpr = block->mChildArr.back();
  8246. }
  8247. else
  8248. break;
  8249. }
  8250. if (!allowRef)
  8251. typedVal = RemoveRef(typedVal);
  8252. }
  8253. }
  8254. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  8255. {
  8256. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsDataIncomplete()) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  8257. {
  8258. if (typedVal.mValue.IsFake())
  8259. {
  8260. InternalError("Unexpected fakeval in CreateValueFromExpression");
  8261. typedVal = GetDefaultTypedValue(typedVal.mType);
  8262. }
  8263. }
  8264. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8265. }
  8266. if (wantTypeRef != NULL)
  8267. {
  8268. if (outOrigType != NULL)
  8269. *outOrigType = typedVal.mType;
  8270. if (((flags & BfEvalExprFlags_NoCast) == 0) && (!wantTypeRef->IsVar()))
  8271. {
  8272. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  8273. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  8274. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  8275. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  8276. if (!typedVal)
  8277. return typedVal;
  8278. }
  8279. if (exprEvaluator.mIsVolatileReference)
  8280. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8281. }
  8282. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  8283. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8284. if (auto autoComplete = mCompiler->GetAutoComplete())
  8285. autoComplete->CheckResult(expr, typedVal);
  8286. return typedVal;
  8287. }
  8288. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  8289. {
  8290. BfExprEvaluator exprEvaluator(this);
  8291. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  8292. }
  8293. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  8294. {
  8295. BfExprEvaluator exprEvaluator(this);
  8296. exprEvaluator.Evaluate(expr);
  8297. if (!exprEvaluator.mResult)
  8298. {
  8299. Fail("Invalid expression type", expr);
  8300. return BfTypedValue();
  8301. }
  8302. if (!exprEvaluator.mResult.IsAddr())
  8303. {
  8304. Fail("Cannot assign to value", expr);
  8305. return BfTypedValue();
  8306. }
  8307. return exprEvaluator.mResult;
  8308. }
  8309. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  8310. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue, BfAllocFlags allocFlags)
  8311. {
  8312. auto typeInstance = typedValue.mType->ToTypeInstance();
  8313. if (zeroMemory)
  8314. {
  8315. int zeroAlign = typedValue.mType->mAlign;
  8316. if (typeInstance != NULL)
  8317. zeroAlign = typeInstance->mInstAlign;
  8318. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  8319. }
  8320. if (!typedValue.mType->IsObject())
  8321. {
  8322. return;
  8323. }
  8324. if ((scopeData == NULL) && (mCurMethodState != NULL))
  8325. return; // Handled in heap alloc funcs
  8326. auto typeDef = typeInstance->mTypeDef;
  8327. mBfIRBuilder->PopulateType(typedValue.mType);
  8328. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  8329. bool isAutocomplete = mCompiler->IsAutocomplete();
  8330. BfIRValue vDataRef;
  8331. if (!isAutocomplete)
  8332. {
  8333. vDataRef = GetClassVDataPtr(typeInstance);
  8334. }
  8335. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8336. auto ptrType = CreatePointerType(i8Type);
  8337. auto ptrPtrType = CreatePointerType(ptrType);
  8338. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  8339. PopulateType(ptrType, BfPopulateType_Declaration);
  8340. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  8341. if (!isAutocomplete)
  8342. {
  8343. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8344. {
  8345. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8346. SizedArray<BfIRValue, 4> llvmArgs;
  8347. llvmArgs.push_back(objectPtr);
  8348. llvmArgs.push_back(vDataRef);
  8349. llvmArgs.push_back(sizeValue);
  8350. llvmArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_Int8, allocFlags));
  8351. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  8352. if (objectStackInitMethod)
  8353. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  8354. }
  8355. else
  8356. {
  8357. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  8358. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  8359. mBfIRBuilder->CreateStore(srcVal, destAddr);
  8360. }
  8361. }
  8362. }
  8363. bool BfModule::IsAllocatorAligned()
  8364. {
  8365. if (mCompiler->mOptions.mMallocLinkName == "StompAlloc")
  8366. return false;
  8367. return true;
  8368. }
  8369. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  8370. {
  8371. BfIRValue result;
  8372. BfType* ptrType;
  8373. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  8374. ptrType = type;
  8375. else
  8376. ptrType = CreatePointerType(type);
  8377. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  8378. {
  8379. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8380. SizedArray<BfExpression*, 2> argExprs;
  8381. BfTypedValueExpression typedValueExpr;
  8382. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  8383. typedValueExpr.mRefNode = refNode;
  8384. argExprs.push_back(&typedValueExpr);
  8385. BfTypedValueExpression appendSizeValueExpr;
  8386. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  8387. appendSizeValueExpr.mRefNode = refNode;
  8388. argExprs.push_back(&appendSizeValueExpr);
  8389. BfExprEvaluator exprEvaluator(this);
  8390. BfTypedValue allocResult;
  8391. if (allocTarget.mScopedInvocationTarget != NULL)
  8392. {
  8393. SizedArray<BfTypeReference*, 2> genericArgs;
  8394. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, BfMethodGenericArguments());
  8395. allocResult = LoadValue(exprEvaluator.mResult);
  8396. }
  8397. else if (allocTarget.mCustomAllocator)
  8398. {
  8399. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8400. if (customTypeInst == NULL)
  8401. {
  8402. if (allocTarget.mCustomAllocator.mType->IsStructPtr())
  8403. customTypeInst = allocTarget.mCustomAllocator.mType->GetUnderlyingType()->ToTypeInstance();
  8404. }
  8405. if (customTypeInst == NULL)
  8406. {
  8407. Fail(StrFormat("Type '%s' cannot be used as a custom allocator", TypeToString(allocTarget.mCustomAllocator.mType).c_str()), refNode);
  8408. }
  8409. else
  8410. {
  8411. BfTypedValueExpression typeValueExpr;
  8412. String allocMethodName = "Alloc";
  8413. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  8414. {
  8415. allocMethodName = "AllocTyped";
  8416. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  8417. auto typeRefVal = CreateTypeDataRef(type);
  8418. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  8419. typeValueExpr.mRefNode = refNode;
  8420. argExprs.Insert(0, &typeValueExpr);
  8421. }
  8422. if (HasMixin(customTypeInst, allocMethodName, 2))
  8423. {
  8424. BfSizedArray<BfExpression*> argExprArr;
  8425. argExprArr.mSize = (int)argExprs.size();
  8426. argExprArr.mVals = &argExprs[0];
  8427. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  8428. allocResult = exprEvaluator.GetResult();
  8429. }
  8430. else
  8431. {
  8432. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8433. BfResolvedArgs argValues(&sizedArgExprs);
  8434. exprEvaluator.ResolveArgValues(argValues);
  8435. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  8436. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, BfMethodGenericArguments());
  8437. }
  8438. }
  8439. }
  8440. if (allocResult)
  8441. {
  8442. if (allocResult.mType->IsVoidPtr())
  8443. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  8444. else
  8445. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  8446. return result;
  8447. }
  8448. }
  8449. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  8450. return result;
  8451. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8452. {
  8453. BfIRValue allocData = GetDbgRawAllocData(type);
  8454. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  8455. SizedArray<BfIRValue, 2> llvmArgs;
  8456. llvmArgs.push_back(sizeValue);
  8457. llvmArgs.push_back(allocData);
  8458. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  8459. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8460. }
  8461. BfModuleMethodInstance moduleMethodInstance;
  8462. moduleMethodInstance = GetInternalMethod("Malloc");
  8463. SizedArray<BfIRValue, 1> llvmArgs;
  8464. llvmArgs.push_back(sizeValue);
  8465. auto func = moduleMethodInstance.mFunc;
  8466. if ((!func) || (func.IsFake()))
  8467. {
  8468. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  8469. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  8470. }
  8471. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  8472. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  8473. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  8474. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8475. return result;
  8476. }
  8477. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  8478. {
  8479. if (type->IsStruct())
  8480. {
  8481. auto typeInstance = type->ToTypeInstance();
  8482. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  8483. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8484. }
  8485. else if (type->IsObjectOrInterface())
  8486. {
  8487. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8488. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  8489. BF_ASSERT(moduleMethodInst.mFunc);
  8490. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8491. }
  8492. else
  8493. {
  8494. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8495. BfExprEvaluator exprEvaluator(this);
  8496. SizedArray<BfResolvedArg, 1> resolvedArgs;
  8497. BfResolvedArg resolvedArg;
  8498. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  8499. resolvedArgs.Add(resolvedArg);
  8500. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, BfMethodGenericArguments());
  8501. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  8502. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  8503. BF_ASSERT(moduleMethodInst.mFunc);
  8504. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8505. }
  8506. return BfIRValue();
  8507. }
  8508. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  8509. {
  8510. BfIRValue allocDataValue;
  8511. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  8512. return allocDataValue;
  8513. BfIRValue markFuncPtr;
  8514. if (type->WantsGCMarking())
  8515. markFuncPtr = GetMarkFuncPtr(type);
  8516. else
  8517. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8518. BfIRValue typeDataRef = CreateTypeDataRef(type);
  8519. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  8520. BfTypeInstance* typeInstance = type->ToTypeInstance();
  8521. if (typeInstance == NULL)
  8522. {
  8523. typeInstance = GetWrappedStructType(type);
  8524. if (typeInstance != NULL)
  8525. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8526. }
  8527. if (typeInstance != NULL)
  8528. PopulateType(typeInstance);
  8529. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8530. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  8531. {
  8532. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8533. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8534. }
  8535. SizedArray<BfIRValue, 2> dataValues;
  8536. dataValues.Add(mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  8537. dataValues.Add(typeDataRef);
  8538. dataValues.Add(markFuncPtr);
  8539. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  8540. BfIRValue dataStruct = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  8541. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  8542. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  8543. return allocDataValue;
  8544. }
  8545. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  8546. {
  8547. BP_ZONE("AllocFromType");
  8548. BfScopeData* scopeData = allocTarget.mScopeData;
  8549. BF_ASSERT(!type->IsVar());
  8550. auto typeInstance = type->ToTypeInstance();
  8551. if ((typeInstance == NULL) && (type->IsGenericParam()))
  8552. typeInstance = mContext->mBfObjectType;
  8553. bool isHeapAlloc = scopeData == NULL;
  8554. bool isScopeAlloc = scopeData != NULL;
  8555. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  8556. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  8557. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  8558. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  8559. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  8560. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  8561. {
  8562. BfPointerType* ptrType = CreatePointerType(type);
  8563. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  8564. return val;
  8565. }
  8566. if (typeInstance != NULL)
  8567. mBfIRBuilder->PopulateType(typeInstance);
  8568. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  8569. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  8570. {
  8571. return mBfIRBuilder->GetFakeVal();
  8572. }
  8573. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8574. BfIRValue sizeValue;
  8575. BfIRType allocType = mBfIRBuilder->MapType(type);
  8576. int allocSize = type->mSize;
  8577. int allocAlign = type->mAlign;
  8578. if (typeInstance != NULL)
  8579. {
  8580. if ((!mBfIRBuilder->mIgnoreWrites) && (!mIsComptimeModule))
  8581. typeInstance->mHasBeenInstantiated = true;
  8582. allocSize = typeInstance->mInstSize;
  8583. allocAlign = typeInstance->mInstAlign;
  8584. //if (typeInstance->IsEnum())
  8585. //allocType = typeInstance->mIRType;
  8586. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  8587. }
  8588. if (alignOverride != -1)
  8589. allocAlign = alignOverride;
  8590. // The "dynSize" cases:
  8591. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  8592. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  8593. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  8594. // though we'd expect their stack space to be released
  8595. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  8596. {
  8597. MarkDynStack(scopeData);
  8598. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8599. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  8600. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  8601. BfType* voidPtrType = CreatePointerType(voidType);
  8602. if (!mCurMethodState->mDynStackRevIdx)
  8603. {
  8604. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  8605. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8606. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8607. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  8608. mBfIRBuilder->ClearDebugLocation(storeInst);
  8609. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8610. }
  8611. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  8612. auto bytePtrType = CreatePointerType(byteType);
  8613. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  8614. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  8615. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8616. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8617. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  8618. mBfIRBuilder->ClearDebugLocation(storeInst);
  8619. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  8620. mBfIRBuilder->ClearDebugLocation(storeInst);
  8621. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8622. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  8623. if (IsTargetingBeefBackend())
  8624. {
  8625. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  8626. // to ensure there isn't any register collision during looping is just to not allow it to
  8627. // bind to a register at all
  8628. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  8629. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  8630. }
  8631. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  8632. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  8633. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  8634. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  8635. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  8636. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  8637. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  8638. mBfIRBuilder->AddBlock(verCheckBB);
  8639. mBfIRBuilder->SetInsertPoint(verCheckBB);
  8640. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  8641. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  8642. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  8643. mBfIRBuilder->AddBlock(resizeBB);
  8644. mBfIRBuilder->SetInsertPoint(resizeBB);
  8645. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8646. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  8647. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  8648. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  8649. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  8650. mBfIRBuilder->CreateBr(endBB);
  8651. mBfIRBuilder->AddBlock(endBB);
  8652. mBfIRBuilder->SetInsertPoint(endBB);
  8653. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  8654. };
  8655. if (isScopeAlloc)
  8656. {
  8657. if (arraySize)
  8658. {
  8659. bool isConstantArraySize = arraySize.IsConst();
  8660. if (isRawArrayAlloc)
  8661. {
  8662. BfPointerType* ptrType = CreatePointerType(type);
  8663. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8664. {
  8665. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8666. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  8667. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  8668. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  8669. }
  8670. else
  8671. {
  8672. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8673. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  8674. if (!isDynAlloc)
  8675. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8676. else
  8677. {
  8678. MarkDynStack(scopeData);
  8679. SaveStackState(scopeData);
  8680. }
  8681. int typeSize = type->GetStride();
  8682. BfIRValue allocaInst;
  8683. BfIRValue result;
  8684. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  8685. {
  8686. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  8687. result = allocaInst;
  8688. }
  8689. else
  8690. {
  8691. if (typeInstance->IsStruct())
  8692. typeSize = typeInstance->GetInstStride();
  8693. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  8694. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  8695. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8696. auto ptrType = CreatePointerType(typeInstance);
  8697. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  8698. if (!isDynAlloc)
  8699. mBfIRBuilder->ClearDebugLocation(result);
  8700. }
  8701. if (!isDynAlloc)
  8702. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8703. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8704. if (!isDynAlloc)
  8705. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8706. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  8707. if (arraySize.IsConst())
  8708. {
  8709. auto constant = mBfIRBuilder->GetConstant(arraySize);
  8710. if (constant->mInt64 == 0)
  8711. noDtorCall = true;
  8712. }
  8713. if (!noDtorCall)
  8714. {
  8715. bool isConstSize = arraySize.IsConst();
  8716. BfIRBlock clearBlock;
  8717. BfIRBlock contBlock;
  8718. bool wantsDeinit = ((!IsOptimized()) && (!mIsComptimeModule) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly));
  8719. if (wantsDeinit)
  8720. {
  8721. BfIRBlock prevBlock;
  8722. if (!isConstSize)
  8723. {
  8724. clearBlock = mBfIRBuilder->CreateBlock("clear");
  8725. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  8726. prevBlock = mBfIRBuilder->GetInsertBlock();
  8727. mBfIRBuilder->AddBlock(clearBlock);
  8728. mBfIRBuilder->SetInsertPoint(clearBlock);
  8729. }
  8730. auto deferredCall = AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  8731. if (!isConstSize)
  8732. {
  8733. mBfIRBuilder->CreateBr(contBlock);
  8734. mBfIRBuilder->SetInsertPoint(prevBlock);
  8735. if (deferredCall != NULL)
  8736. {
  8737. // Zero out size args
  8738. for (int i = 1; i < deferredCall->mModuleMethodInstance.mMethodInstance->GetParamCount(); i++)
  8739. {
  8740. auto scopedArg = deferredCall->mScopeArgs[i];
  8741. if (scopedArg != deferredCall->mOrigScopeArgs[i])
  8742. mBfIRBuilder->CreateStore(GetDefaultValue(deferredCall->mModuleMethodInstance.mMethodInstance->GetParamType(i)), deferredCall->mScopeArgs[i]);
  8743. }
  8744. }
  8745. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  8746. mBfIRBuilder->AddBlock(contBlock);
  8747. mBfIRBuilder->SetInsertPoint(contBlock);
  8748. }
  8749. }
  8750. }
  8751. return result;
  8752. }
  8753. }
  8754. else
  8755. {
  8756. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8757. {
  8758. // Generate and check new size
  8759. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8760. auto firstElementField = &arrayType->mFieldInstances.back();
  8761. int arrayClassSize = firstElementField->mDataOffset;
  8762. sizeValue = GetConstValue(arrayClassSize);
  8763. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8764. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8765. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  8766. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  8767. if (!noDtorCall)
  8768. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8769. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8770. return typedVal.mValue;
  8771. }
  8772. else
  8773. {
  8774. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8775. auto firstElementField = &arrayType->mFieldInstances.back();
  8776. if (!type->IsValuelessType())
  8777. {
  8778. int arrayClassSize = firstElementField->mDataOffset;
  8779. sizeValue = GetConstValue(arrayClassSize);
  8780. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8781. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8782. }
  8783. else
  8784. sizeValue = GetConstValue(arrayType->mInstSize);
  8785. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8786. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8787. if (!isDynAlloc)
  8788. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8789. else
  8790. {
  8791. MarkDynStack(scopeData);
  8792. SaveStackState(scopeData);
  8793. }
  8794. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  8795. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8796. if (!isDynAlloc)
  8797. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8798. auto allocaBlock = mBfIRBuilder->GetInsertBlock();
  8799. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8800. BfTypedValue typedVal;
  8801. if (!isDynAlloc)
  8802. {
  8803. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8804. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8805. mBfIRBuilder->ClearDebugLocation(typedVal.mValue);
  8806. mBfIRBuilder->SetInsertPoint(prevBlock);
  8807. allocaBlock = mCurMethodState->mIRInitBlock;
  8808. }
  8809. else
  8810. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8811. if (!noDtorCall)
  8812. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true, allocaBlock);
  8813. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8814. return typedVal.mValue;
  8815. }
  8816. }
  8817. }
  8818. else if (appendSizeValue)
  8819. {
  8820. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  8821. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  8822. // use the "dynSize" version conservatively
  8823. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8824. {
  8825. // Generate and check new size
  8826. sizeValue = GetConstValue(typeInstance->mInstSize);
  8827. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8828. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  8829. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  8830. if (!noDtorCall)
  8831. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  8832. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8833. return typedVal.mValue;
  8834. }
  8835. else // stack alloc, unlooped, with append
  8836. {
  8837. sizeValue = GetConstValue(typeInstance->mInstSize);
  8838. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8839. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8840. bool wasDynAlloc = isDynAlloc;
  8841. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8842. if (!isDynAlloc)
  8843. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8844. else
  8845. {
  8846. MarkDynStack(scopeData);
  8847. SaveStackState(scopeData);
  8848. }
  8849. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  8850. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  8851. if (!isDynAlloc)
  8852. {
  8853. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8854. }
  8855. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8856. bool mayBeLarge = false;
  8857. if (sizeValue.IsConst())
  8858. {
  8859. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  8860. if (constantInt->mInt64 >= 4096)
  8861. mayBeLarge = true;
  8862. }
  8863. else
  8864. mayBeLarge = true;
  8865. if (((type->IsObject() && (!mayBeLarge))) ||
  8866. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8867. ((zeroMemory) && (!mayBeLarge)))
  8868. {
  8869. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8870. }
  8871. BfIRValue castedVal;
  8872. if (!isDynAlloc)
  8873. {
  8874. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8875. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8876. mBfIRBuilder->ClearDebugLocation(castedVal);
  8877. mBfIRBuilder->SetInsertPoint(prevBlock);
  8878. if (WantsLifetimes())
  8879. {
  8880. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8881. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8882. }
  8883. }
  8884. else
  8885. {
  8886. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8887. }
  8888. auto typedVal = BfTypedValue(castedVal, typeInstance);
  8889. if (!noDtorCall)
  8890. {
  8891. bool doCondAlloca = false;
  8892. if (!IsTargetingBeefBackend())
  8893. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  8894. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  8895. }
  8896. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue, allocFlags);
  8897. return typedVal.mValue;
  8898. }
  8899. }
  8900. else // "Normal" stack alloc
  8901. {
  8902. BF_ASSERT(!sizeValue);
  8903. //TODO: If sizeValue is a constant then do this in the head IR builder
  8904. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8905. if (!isLoopedAlloc)
  8906. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8907. else
  8908. {
  8909. MarkDynStack(scopeData);
  8910. SaveStackState(scopeData);
  8911. }
  8912. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  8913. if (!isLoopedAlloc)
  8914. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8915. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8916. bool mayBeLarge = allocSize >= 4096;
  8917. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  8918. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8919. ((zeroMemory) && (!mayBeLarge)))
  8920. {
  8921. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  8922. // and memset is always safe
  8923. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8924. }
  8925. auto typedVal = BfTypedValue(allocaInst, type);
  8926. if (!isLoopedAlloc)
  8927. {
  8928. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8929. mBfIRBuilder->SetInsertPoint(prevBlock);
  8930. if (WantsLifetimes())
  8931. {
  8932. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8933. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8934. }
  8935. }
  8936. if (!noDtorCall)
  8937. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8938. if (typeInstance != NULL)
  8939. {
  8940. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  8941. }
  8942. else
  8943. {
  8944. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  8945. }
  8946. return allocaInst;
  8947. }
  8948. }
  8949. else if (arraySize)
  8950. {
  8951. if (isRawArrayAlloc)
  8952. {
  8953. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8954. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  8955. }
  8956. else
  8957. {
  8958. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8959. typeInstance = arrayType;
  8960. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8961. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8962. appendSizeValue = elementDataSize;
  8963. if (!type->IsSizeAligned())
  8964. {
  8965. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  8966. }
  8967. }
  8968. }
  8969. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  8970. {
  8971. auto vDataRef = GetClassVDataPtr(typeInstance);
  8972. BfIRValue result;
  8973. bool isResultInitialized = false;
  8974. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8975. if (typeInstance->mTypeOptionsIdx != -1)
  8976. {
  8977. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8978. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8979. }
  8980. if (mIsComptimeModule)
  8981. stackCount = 0;
  8982. if (!sizeValue)
  8983. sizeValue = GetConstValue(typeInstance->mInstSize);
  8984. if (appendSizeValue)
  8985. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8986. BfIRValue origSizeValue = sizeValue;
  8987. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  8988. if (isAllocEx)
  8989. {
  8990. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  8991. if (prepareStackTraceMethod)
  8992. {
  8993. SizedArray<BfIRValue, 2> irArgs;
  8994. irArgs.Add(sizeValue);
  8995. irArgs.Add(GetConstValue(stackCount));
  8996. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  8997. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  8998. }
  8999. }
  9000. if (allocTarget.mCustomAllocator)
  9001. {
  9002. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  9003. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  9004. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  9005. {
  9006. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  9007. mBfIRBuilder->PopulateType(classVDataType);
  9008. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  9009. mBfIRBuilder->PopulateType(typeInstType);
  9010. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  9011. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  9012. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  9013. BfTypedValueExpression typedValueExpr;
  9014. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  9015. typedValueExpr.mRefNode = allocTarget.mRefNode;
  9016. BfExprEvaluator exprEvaluator(this);
  9017. SizedArray<BfExpression*, 2> argExprs;
  9018. argExprs.push_back(&typedValueExpr);
  9019. BfTypedValueExpression sizeValueExpr;
  9020. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  9021. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  9022. argExprs.push_back(&sizeValueExpr);
  9023. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  9024. BfResolvedArgs argValues(&sizedArgExprs);
  9025. exprEvaluator.ResolveArgValues(argValues);
  9026. exprEvaluator.mNoBind = true;
  9027. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, BfMethodGenericArguments());
  9028. if (allocResult)
  9029. {
  9030. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  9031. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  9032. else
  9033. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  9034. isResultInitialized = true;
  9035. }
  9036. }
  9037. }
  9038. bool wasAllocated = false;
  9039. if (!result)
  9040. {
  9041. if (hasCustomAllocator)
  9042. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  9043. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  9044. {
  9045. SizedArray<BfIRValue, 4> llvmArgs;
  9046. llvmArgs.push_back(sizeValue);
  9047. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  9048. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  9049. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  9050. wasAllocated = true;
  9051. }
  9052. }
  9053. if (result)
  9054. {
  9055. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9056. {
  9057. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  9058. SizedArray<BfIRValue, 4> llvmArgs;
  9059. llvmArgs.push_back(objectPtr);
  9060. llvmArgs.push_back(origSizeValue);
  9061. llvmArgs.push_back(vDataRef);
  9062. if (isAllocEx)
  9063. llvmArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_Int8, allocFlags));
  9064. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  9065. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  9066. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  9067. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  9068. if (wasAllocated)
  9069. {
  9070. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  9071. auto bytePtrType = CreatePointerType(byteType);
  9072. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  9073. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  9074. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  9075. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  9076. }
  9077. }
  9078. else
  9079. {
  9080. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  9081. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  9082. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  9083. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  9084. }
  9085. }
  9086. else
  9087. {
  9088. if ((mBfIRBuilder->mIgnoreWrites) ||
  9089. ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)))
  9090. {
  9091. if (mBfIRBuilder->mIgnoreWrites)
  9092. {
  9093. return GetDefaultValue(typeInstance);
  9094. }
  9095. else
  9096. {
  9097. // Fake with alloca
  9098. mBfIRBuilder->PopulateType(typeInstance);
  9099. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInstance));
  9100. }
  9101. }
  9102. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  9103. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  9104. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9105. {
  9106. SizedArray<BfIRValue, 4> llvmArgs;
  9107. llvmArgs.push_back(vData);
  9108. llvmArgs.push_back(sizeValue);
  9109. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  9110. llvmArgs.push_back(GetConstValue(stackCount));
  9111. llvmArgs.push_back(GetConstValue(allocFlags, GetPrimitiveType(BfTypeCode_Int8)));
  9112. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 5);
  9113. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  9114. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  9115. }
  9116. else
  9117. {
  9118. SizedArray<BfIRValue, 4> llvmArgs;
  9119. llvmArgs.push_back(sizeValue);
  9120. BfIRFunction irFunc;
  9121. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  9122. {
  9123. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  9124. irFunc = moduleMethodInstance.mFunc;
  9125. }
  9126. if (!irFunc)
  9127. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  9128. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  9129. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  9130. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  9131. if (mIsComptimeModule)
  9132. {
  9133. vdataPtr = mBfIRBuilder->CreateBitCast(vdataPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance())));
  9134. }
  9135. mBfIRBuilder->CreateStore(vData, vdataPtr);
  9136. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  9137. }
  9138. }
  9139. if ((zeroMemory) && (arraySize))
  9140. {
  9141. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  9142. typeInstance = arrayType;
  9143. auto firstElementField = &arrayType->mFieldInstances.back();
  9144. int arrayClassSize = firstElementField->mDataOffset;
  9145. BfIRValue elementDataSize;
  9146. bool skipZero = false;
  9147. if (arraySize.IsConst())
  9148. {
  9149. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  9150. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  9151. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  9152. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  9153. if (constVal->mInt64 <= 0)
  9154. skipZero = true;
  9155. }
  9156. else
  9157. {
  9158. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  9159. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  9160. }
  9161. if (!skipZero)
  9162. {
  9163. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  9164. auto ptrType = CreatePointerType(i8Type);
  9165. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  9166. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  9167. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  9168. appendSizeValue = elementDataSize;
  9169. }
  9170. }
  9171. return result;
  9172. }
  9173. else
  9174. {
  9175. if (!sizeValue)
  9176. sizeValue = GetConstValue(allocSize);
  9177. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  9178. }
  9179. }
  9180. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  9181. {
  9182. if ((type == NULL) || (refNode == NULL))
  9183. return;
  9184. auto typeInstance = type->ToTypeInstance();
  9185. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  9186. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  9187. }
  9188. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  9189. {
  9190. if (align <= 1)
  9191. return;
  9192. if (sizeMultiple == 0)
  9193. sizeMultiple = align;
  9194. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  9195. {
  9196. if (!IsAllocatorAligned())
  9197. {
  9198. // Don't align
  9199. }
  9200. else if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  9201. {
  9202. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  9203. BF_ASSERT(localVar->mName == "__appendIdx");
  9204. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  9205. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9206. if (align > 1)
  9207. {
  9208. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  9209. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  9210. }
  9211. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  9212. }
  9213. else
  9214. {
  9215. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  9216. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  9217. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  9218. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  9219. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  9220. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  9221. }
  9222. }
  9223. if (mCurMethodState->mCurAppendAlign == 0)
  9224. mCurMethodState->mCurAppendAlign = sizeMultiple;
  9225. else
  9226. {
  9227. if (sizeMultiple % align == 0)
  9228. mCurMethodState->mCurAppendAlign = align;
  9229. else
  9230. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  9231. }
  9232. }
  9233. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  9234. {
  9235. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  9236. BF_ASSERT(localVar->mName == "__appendIdx");
  9237. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  9238. BfIRValue retValue;
  9239. BfTypeInstance* retTypeInstance = NULL;
  9240. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  9241. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  9242. if (arraySize)
  9243. {
  9244. if (isRawArrayAlloc)
  9245. {
  9246. EmitAppendAlign(type->mAlign);
  9247. BfPointerType* ptrType = CreatePointerType(type);
  9248. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  9249. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9250. if (mSystem->mPtrSize != 4)
  9251. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  9252. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9253. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9254. if (zeroMemory)
  9255. {
  9256. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  9257. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  9258. }
  9259. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  9260. }
  9261. else
  9262. {
  9263. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  9264. EmitAppendAlign(arrayType->mAlign, type->mSize);
  9265. auto firstElementField = &arrayType->mFieldInstances.back();
  9266. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  9267. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  9268. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  9269. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  9270. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9271. if (mSystem->mPtrSize != 4)
  9272. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  9273. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9274. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9275. if (zeroMemory)
  9276. {
  9277. // Only zero out the actual elements
  9278. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  9279. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  9280. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  9281. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  9282. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  9283. }
  9284. retTypeInstance = arrayType;
  9285. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  9286. }
  9287. }
  9288. else
  9289. {
  9290. auto typeInst = type->ToTypeInstance();
  9291. BfIRValue sizeValue;
  9292. BfIRType toType;
  9293. if (typeInst != NULL)
  9294. {
  9295. mBfIRBuilder->PopulateType(typeInst);
  9296. if (typeInst->WantsGCMarking())
  9297. mCurTypeInstance->mHasAppendWantMark = true;
  9298. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  9299. sizeValue = GetConstValue(typeInst->mInstSize);
  9300. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  9301. }
  9302. else
  9303. {
  9304. EmitAppendAlign(type->mAlign, type->mSize);
  9305. sizeValue = GetConstValue(type->mSize);
  9306. auto toPtrType = CreatePointerType(type);
  9307. toType = mBfIRBuilder->MapType(toPtrType);
  9308. }
  9309. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9310. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9311. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9312. retTypeInstance = typeInst;
  9313. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  9314. if ((typeInst != NULL) && (typeInst->WantsGCMarking()) && (mCompiler->mOptions.mDebugAlloc))
  9315. {
  9316. auto curThis = GetThis();
  9317. auto thisObj = Cast(mCurMethodInstance->mMethodDef->GetRefNode(), curThis, mContext->mBfObjectType);
  9318. if (typeInst->IsObject())
  9319. {
  9320. auto appendedObj = Cast(mCurMethodInstance->mMethodDef->GetRefNode(), BfTypedValue(retValue, typeInst), mContext->mBfObjectType);
  9321. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_ObjectAppended", 2);
  9322. SizedArray<BfIRValue, 2> llvmArgs;
  9323. llvmArgs.push_back(thisObj.mValue);
  9324. llvmArgs.push_back(appendedObj.mValue);
  9325. mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  9326. }
  9327. else
  9328. {
  9329. // Raw
  9330. BfIRValue allocPtr = mBfIRBuilder->CreateBitCast(retValue, mBfIRBuilder->MapType(voidPtrType));
  9331. BfIRValue allocData = GetDbgRawAllocData(type);
  9332. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAppended", 3);
  9333. SizedArray<BfIRValue, 3> llvmArgs;
  9334. llvmArgs.push_back(thisObj.mValue);
  9335. llvmArgs.push_back(allocPtr);
  9336. llvmArgs.push_back(allocData);
  9337. mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  9338. }
  9339. }
  9340. }
  9341. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  9342. {
  9343. mBfIRBuilder->PopulateType(retTypeInstance);
  9344. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  9345. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  9346. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  9347. auto curThis = GetThis();
  9348. BfIRValue newFlags;
  9349. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9350. {
  9351. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  9352. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  9353. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  9354. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  9355. }
  9356. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  9357. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  9358. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  9359. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  9360. mBfIRBuilder->CreateStore(srcVal, destAddr);
  9361. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9362. {
  9363. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  9364. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  9365. }
  9366. }
  9367. if (appendSizeValue)
  9368. {
  9369. EmitAppendAlign(appendAllocAlign);
  9370. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9371. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  9372. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9373. }
  9374. return retValue;
  9375. }
  9376. bool BfModule::IsOptimized()
  9377. {
  9378. if (mProject == NULL)
  9379. return false;
  9380. if (mIsComptimeModule)
  9381. return false;
  9382. int optLevel = GetModuleOptions().mOptLevel;
  9383. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  9384. }
  9385. bool BfModule::IsTargetingBeefBackend()
  9386. {
  9387. if (mProject == NULL)
  9388. return true;
  9389. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9390. }
  9391. bool BfModule::WantsLifetimes()
  9392. {
  9393. if (mBfIRBuilder->mIgnoreWrites)
  9394. return false;
  9395. if ((mIsComptimeModule) && (mBfIRBuilder->HasDebugLocation()))
  9396. return true;
  9397. else if (mProject == NULL)
  9398. return false;
  9399. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9400. }
  9401. bool BfModule::HasCompiledOutput()
  9402. {
  9403. return (!mSystem->mIsResolveOnly) && (mGeneratesCode) && (!mIsComptimeModule);
  9404. }
  9405. bool BfModule::HasExecutedOutput()
  9406. {
  9407. return ((!mSystem->mIsResolveOnly) && (mGeneratesCode)) || (mIsComptimeModule);
  9408. }
  9409. // We will skip the object access check for any occurrences of this value
  9410. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  9411. {
  9412. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9413. return;
  9414. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9415. return;
  9416. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  9417. return;
  9418. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  9419. }
  9420. bool BfModule::WantsObjectAccessCheck(BfType* type)
  9421. {
  9422. if ((mBfIRBuilder->mIgnoreWrites) || (!type->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9423. return false;
  9424. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9425. return false;
  9426. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9427. auto typeOptions = GetTypeOptions();
  9428. if (typeOptions != NULL)
  9429. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9430. if (!emitObjectAccessCheck)
  9431. return false;
  9432. return true;
  9433. }
  9434. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  9435. {
  9436. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9437. return;
  9438. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9439. return;
  9440. if (typedVal.mValue.IsConst())
  9441. {
  9442. int stringIdx = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  9443. if (stringIdx != -1)
  9444. return;
  9445. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  9446. if (constant->mTypeCode == BfTypeCode_NullPtr)
  9447. return;
  9448. if (constant->mConstType == BfConstType_BitCastNull)
  9449. return;
  9450. }
  9451. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9452. auto typeOptions = GetTypeOptions();
  9453. if (typeOptions != NULL)
  9454. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9455. if (!emitObjectAccessCheck)
  9456. return;
  9457. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  9458. {
  9459. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  9460. return;
  9461. }
  9462. if (typedVal.IsAddr())
  9463. typedVal = LoadValue(typedVal);
  9464. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  9465. }
  9466. bool BfModule::WantsDebugHelpers()
  9467. {
  9468. if (mBfIRBuilder->mIgnoreWrites)
  9469. return false;
  9470. if (mIsComptimeModule)
  9471. {
  9472. // Always add
  9473. }
  9474. else if ((mProject == NULL) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  9475. return false;
  9476. return true;
  9477. }
  9478. void BfModule::EmitEnsureInstructionAt()
  9479. {
  9480. if (!WantsDebugHelpers())
  9481. return;
  9482. mBfIRBuilder->CreateEnsureInstructionAt();
  9483. }
  9484. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  9485. {
  9486. if (mBfIRBuilder->mIgnoreWrites)
  9487. return; // Nothing needed here
  9488. auto irb = mBfIRBuilder;
  9489. auto checkBB = irb->CreateBlock("as.check");
  9490. auto isNull = irb->CreateIsNull(targetValue.mValue);
  9491. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  9492. if (mIsComptimeModule)
  9493. {
  9494. AddBasicBlock(checkBB);
  9495. auto callResult = mBfIRBuilder->Comptime_DynamicCastCheck(targetValue.mValue, targetType->mTypeId, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9496. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult, GetDefaultValue(mContext->mBfObjectType));
  9497. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9498. return;
  9499. }
  9500. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  9501. auto intPtrType = CreatePointerType(intType);
  9502. auto intPtrPtrType = CreatePointerType(intPtrType);
  9503. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  9504. auto int32PtrType = CreatePointerType(int32Type);
  9505. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  9506. if (targetType->IsDelegate())
  9507. {
  9508. // Delegate signature check
  9509. int signatureId = GetDelegateSignatureId(targetType->ToTypeInstance());
  9510. BfExprEvaluator exprEvaluator(this);
  9511. AddBasicBlock(checkBB);
  9512. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9513. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, "DynamicCastToSignature");
  9514. SizedArray<BfIRValue, 4> irArgs;
  9515. irArgs.push_back(objectParam);
  9516. irArgs.push_back(GetConstValue32(signatureId));
  9517. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  9518. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  9519. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9520. }
  9521. else if (mCompiler->mOptions.mAllowHotSwapping)
  9522. {
  9523. // "Slow" check
  9524. BfExprEvaluator exprEvaluator(this);
  9525. AddBasicBlock(checkBB);
  9526. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9527. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  9528. SizedArray<BfIRValue, 4> irArgs;
  9529. irArgs.push_back(objectParam);
  9530. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  9531. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  9532. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  9533. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9534. }
  9535. else
  9536. {
  9537. AddBasicBlock(checkBB);
  9538. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  9539. vDataPtr = irb->CreateLoad(vDataPtr);
  9540. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9541. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  9542. if (targetType->IsInterface())
  9543. {
  9544. auto targetTypeInst = targetType->ToTypeInstance();
  9545. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9546. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  9547. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  9548. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9549. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  9550. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  9551. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  9552. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  9553. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  9554. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9555. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  9556. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  9557. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9558. }
  9559. else
  9560. {
  9561. if (!targetType->IsTypeInstance())
  9562. targetType = GetWrappedStructType(targetType);
  9563. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9564. int inheritanceIdOfs = mSystem->mPtrSize * mCompiler->GetVDataPrefixDataCount();
  9565. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9566. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9567. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  9568. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  9569. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  9570. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  9571. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  9572. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9573. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  9574. fieldInst = &typeTypeInstance->mFieldInstances[10];
  9575. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  9576. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9577. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  9578. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  9579. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  9580. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9581. }
  9582. }
  9583. }
  9584. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  9585. {
  9586. if (mBfIRBuilder->mIgnoreWrites)
  9587. return;
  9588. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  9589. auto typeOptions = GetTypeOptions();
  9590. if (typeOptions != NULL)
  9591. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  9592. if (emitDynamicCastCheck)
  9593. {
  9594. int wantTypeId = 0;
  9595. if (!type->IsGenericParam())
  9596. wantTypeId = type->mTypeId;
  9597. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  9598. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  9599. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  9600. AddBasicBlock(failBlock);
  9601. if (mIsComptimeModule)
  9602. {
  9603. mBfIRBuilder->Comptime_Error(CeErrorKind_ObjectDynCheckFailed);
  9604. }
  9605. else
  9606. {
  9607. SizedArray<BfIRValue, 8> llvmArgs;
  9608. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9609. llvmArgs.push_back(bitAddr);
  9610. llvmArgs.push_back(GetConstValue32(wantTypeId));
  9611. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  9612. BF_ASSERT(objDynCheck);
  9613. if (objDynCheck)
  9614. {
  9615. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  9616. }
  9617. }
  9618. mBfIRBuilder->CreateBr(endBlock);
  9619. AddBasicBlock(endBlock);
  9620. }
  9621. }
  9622. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, BfCastFlags castFlags)
  9623. {
  9624. bool callDtor = (castFlags & BfCastFlags_NoBoxDtor) == 0;
  9625. bool wantConst = ((castFlags & BfCastFlags_WantsConst) != 0) && (typedVal.mValue.IsConst());
  9626. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9627. {
  9628. if (toType == mContext->mBfObjectType)
  9629. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9630. if (toType->IsBoxed())
  9631. {
  9632. BfBoxedType* boxedType = (BfBoxedType*)toType;
  9633. if (boxedType->mElementType->IsGenericParam())
  9634. {
  9635. if (typedVal.mType == boxedType->mElementType)
  9636. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9637. else
  9638. return BfTypedValue();
  9639. }
  9640. }
  9641. }
  9642. BP_ZONE("BoxValue");
  9643. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  9644. if (typedVal.mType->IsNullable())
  9645. {
  9646. typedVal = MakeAddressable(typedVal);
  9647. auto innerType = typedVal.mType->GetUnderlyingType();
  9648. if (!innerType->IsValueType())
  9649. {
  9650. if (!mIgnoreErrors)
  9651. Fail("Only value types can be boxed", srcNode);
  9652. return BfTypedValue();
  9653. }
  9654. auto boxedType = CreateBoxedType(innerType);
  9655. auto resultType = toType;
  9656. if (resultType == NULL)
  9657. resultType = boxedType;
  9658. if (mBfIRBuilder->mIgnoreWrites)
  9659. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  9660. auto prevBB = mBfIRBuilder->GetInsertBlock();
  9661. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  9662. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  9663. mBfIRBuilder->PopulateType(typedVal.mType);
  9664. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  9665. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  9666. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  9667. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9668. mBfIRBuilder->AddBlock(boxBB);
  9669. mBfIRBuilder->SetInsertPoint(boxBB);
  9670. BfScopeData newScope;
  9671. newScope.mOuterIsConditional = true;
  9672. mCurMethodState->AddScope(&newScope);
  9673. NewScopeState();
  9674. BfIRValue nullableValueAddr;
  9675. BfIRValue loadedVal;
  9676. if (innerType->IsValuelessType())
  9677. {
  9678. loadedVal = mBfIRBuilder->GetFakeVal();
  9679. }
  9680. else
  9681. {
  9682. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  9683. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  9684. }
  9685. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor ? BfCastFlags_None : BfCastFlags_NoBoxDtor);
  9686. RestoreScopeState();
  9687. if (!boxedVal)
  9688. return BfTypedValue();
  9689. mBfIRBuilder->CreateBr(endBB);
  9690. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  9691. mBfIRBuilder->AddBlock(endBB);
  9692. mBfIRBuilder->SetInsertPoint(endBB);
  9693. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  9694. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  9695. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  9696. return BfTypedValue(phi, resultType);
  9697. }
  9698. bool alreadyCheckedCast = false;
  9699. BfTypeInstance* toTypeInstance = NULL;
  9700. if (toType != NULL)
  9701. toTypeInstance = toType->ToTypeInstance();
  9702. bool isStructPtr = typedVal.mType->IsStructPtr();
  9703. if (fromStructTypeInstance == NULL)
  9704. {
  9705. auto primType = (BfPrimitiveType*)typedVal.mType;
  9706. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  9707. {
  9708. // Can always do IHashable
  9709. alreadyCheckedCast = true;
  9710. }
  9711. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  9712. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9713. else
  9714. {
  9715. auto checkStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9716. if (checkStructTypeInstance == toType->GetUnderlyingType())
  9717. fromStructTypeInstance = checkStructTypeInstance;
  9718. }
  9719. if (isStructPtr)
  9720. {
  9721. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9722. alreadyCheckedCast = true;
  9723. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  9724. }
  9725. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  9726. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9727. }
  9728. if (fromStructTypeInstance == NULL)
  9729. return BfTypedValue();
  9730. // Need to box it
  9731. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  9732. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9733. {
  9734. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9735. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  9736. auto boxedType = CreateBoxedType(typedVal.mType);
  9737. mBfIRBuilder->PopulateType(boxedType);
  9738. if (wantConst)
  9739. return BfTypedValue(mBfIRBuilder->CreateConstBox(typedVal.mValue, mBfIRBuilder->MapType(boxedType)), boxedType);
  9740. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9741. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  9742. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  9743. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  9744. if (boxedType->IsUnspecializedType())
  9745. {
  9746. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  9747. }
  9748. else
  9749. {
  9750. PopulateType(fromStructTypeInstance);
  9751. if (!fromStructTypeInstance->IsValuelessType())
  9752. {
  9753. typedVal = LoadValue(typedVal);
  9754. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  9755. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  9756. {
  9757. auto ptrType = CreatePointerType(typedVal.mType);
  9758. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  9759. }
  9760. if (typedVal.IsSplat())
  9761. {
  9762. AggregateSplatIntoAddr(typedVal, valPtr);
  9763. }
  9764. else
  9765. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr, typedVal.mType->mAlign);
  9766. }
  9767. }
  9768. if (toType == NULL)
  9769. {
  9770. return BfTypedValue(allocaInst, boxedType);
  9771. }
  9772. else
  9773. {
  9774. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  9775. return BfTypedValue(castedValue, toType);
  9776. }
  9777. }
  9778. return BfTypedValue();
  9779. }
  9780. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  9781. {
  9782. BfTypeInstance* checkTypeInst = typeInst;
  9783. while (checkTypeInst != NULL)
  9784. {
  9785. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  9786. {
  9787. if (checkProp->mName == propDef->mName)
  9788. {
  9789. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  9790. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  9791. {
  9792. propDef = checkProp;
  9793. typeInst = checkTypeInst;
  9794. return true;
  9795. }
  9796. }
  9797. }
  9798. checkTypeInst = checkTypeInst->mBaseType;
  9799. }
  9800. return false;
  9801. }
  9802. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  9803. {
  9804. if (typeInstance->IsDeleting())
  9805. {
  9806. mCompiler->RequestExtraCompile();
  9807. InternalError("GetRawMethodInstanceAtIdx for deleted type", typeInstance->mTypeDef->GetRefNode());
  9808. return NULL;
  9809. }
  9810. if (!typeInstance->mResolvingVarField)
  9811. {
  9812. if (!typeInstance->DefineStateAllowsStaticMethods())
  9813. PopulateType(typeInstance, BfPopulateType_AllowStaticMethods);
  9814. }
  9815. else
  9816. {
  9817. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  9818. {
  9819. AssertErrorState();
  9820. return NULL;
  9821. }
  9822. }
  9823. if (assertName != NULL)
  9824. {
  9825. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9826. }
  9827. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9828. {
  9829. if (mCompiler->EnsureCeUnpaused(typeInstance))
  9830. {
  9831. InternalError("OOB in GetRawMethodInstanceAtIdx");
  9832. }
  9833. return NULL;
  9834. }
  9835. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  9836. if (methodGroup.mDefault == NULL)
  9837. {
  9838. if (!mCompiler->mIsResolveOnly)
  9839. {
  9840. // Get it from the owning module so we don't create a reference prematurely...
  9841. auto declModule = typeInstance->mModule;
  9842. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  9843. {
  9844. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9845. if (!declModule->mIsScratchModule)
  9846. declModule->mOnDemandMethodCount++;
  9847. }
  9848. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  9849. (typeInstance->mTypeFailed) || (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted));
  9850. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  9851. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9852. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified);
  9853. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9854. }
  9855. else
  9856. {
  9857. auto declModule = typeInstance->mModule;
  9858. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass);
  9859. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9860. }
  9861. }
  9862. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9863. //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
  9864. // be from a call to the NON-raw version
  9865. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  9866. // {
  9867. // methodInstance->mIsReified = mIsReified;
  9868. // if (methodInstance->mMethodProcessRequest == NULL)
  9869. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  9870. // }
  9871. return methodInstance;
  9872. }
  9873. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  9874. {
  9875. if (methodDef->mIsLocalMethod)
  9876. {
  9877. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  9878. }
  9879. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx, NULL);
  9880. }
  9881. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  9882. {
  9883. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9884. while (typeInstance != NULL)
  9885. {
  9886. typeInstance->mTypeDef->PopulateMemberSets();
  9887. BfMemberSetEntry* entry = NULL;
  9888. BfMethodDef* methodDef = NULL;
  9889. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9890. methodDef = (BfMethodDef*)entry->mMemberDef;
  9891. while (methodDef != NULL)
  9892. {
  9893. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  9894. (methodDef->mGenericParams.size() == 0) &&
  9895. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9896. return GetRawMethodInstance(typeInstance, methodDef);
  9897. methodDef = methodDef->mNextWithSameName;
  9898. }
  9899. if (!checkBase)
  9900. break;
  9901. typeInstance = typeInstance->mBaseType;
  9902. }
  9903. return NULL;
  9904. }
  9905. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  9906. {
  9907. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9908. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  9909. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  9910. if (!useUnspecializedType)
  9911. return methodInstance;
  9912. if (!owner->IsGenericTypeInstance())
  9913. return methodInstance;
  9914. if ((owner->IsDelegateFromTypeRef()) ||
  9915. (owner->IsFunctionFromTypeRef()) ||
  9916. (owner->IsTuple()))
  9917. {
  9918. return methodInstance;
  9919. }
  9920. auto genericType = (BfTypeInstance*)owner;
  9921. if ((genericType->IsUnspecializedType()) && (!genericType->IsUnspecializedTypeVariation()))
  9922. return methodInstance;
  9923. if (methodInstance->mMethodDef->mIsLocalMethod)
  9924. return methodInstance;
  9925. if (methodInstance->mMethodDef->mDeclaringType->IsEmitted())
  9926. return methodInstance;
  9927. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef->GetDefinition());
  9928. if (unspecializedType == NULL)
  9929. {
  9930. AssertErrorState();
  9931. return methodInstance;
  9932. }
  9933. if (unspecializedType == NULL)
  9934. return methodInstance;
  9935. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  9936. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  9937. }
  9938. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  9939. {
  9940. int genericCount = 0;
  9941. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  9942. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  9943. {
  9944. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  9945. if (param->IsGenericParam())
  9946. genericCount++;
  9947. }
  9948. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  9949. genericCount++;
  9950. return genericCount;
  9951. }
  9952. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  9953. {
  9954. BF_ASSERT(!mIsScratchModule);
  9955. BF_ASSERT(mIsReified);
  9956. BfModule* mainModule = this;
  9957. if (mParentModule != NULL)
  9958. mainModule = mParentModule;
  9959. BfModule* specModule = NULL;
  9960. BfModule** specModulePtr = NULL;
  9961. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  9962. {
  9963. return *specModulePtr;
  9964. }
  9965. else
  9966. {
  9967. String specModuleName = mModuleName;
  9968. for (auto bfProject : projectList)
  9969. {
  9970. specModuleName += StrFormat("@%s", bfProject->mSafeName.c_str());
  9971. }
  9972. specModule = new BfModule(mContext, specModuleName);
  9973. specModule->mProject = mainModule->mProject;
  9974. specModule->mParentModule = mainModule;
  9975. specModule->mIsSpecializedMethodModuleRoot = true;
  9976. specModule->Init();
  9977. Array<BfProject*> projList;
  9978. for (auto project : projectList)
  9979. projList.Add(project);
  9980. mainModule->mSpecializedMethodModules[projList] = specModule;
  9981. }
  9982. return specModule;
  9983. }
  9984. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  9985. {
  9986. if (IsSkippingExtraResolveChecks())
  9987. return BfIRValue();
  9988. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  9989. {
  9990. //BF_ASSERT(!methodInstance->mIRFunction);
  9991. return BfIRValue();
  9992. }
  9993. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  9994. FinishInit();
  9995. auto methodDef = methodInstance->mMethodDef;
  9996. StringT<4096> methodName;
  9997. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  9998. if (isInlined != methodInstance->mAlwaysInline)
  9999. {
  10000. if (isInlined)
  10001. methodName += "__INLINE";
  10002. else
  10003. methodName += "__NOINLINE";
  10004. }
  10005. if (tryExisting)
  10006. {
  10007. auto func = mBfIRBuilder->GetFunction(methodName);
  10008. if (func)
  10009. return func;
  10010. }
  10011. auto intrinsic = GetIntrinsic(methodInstance);
  10012. if (intrinsic)
  10013. return intrinsic;
  10014. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  10015. {
  10016. return CreateDllImportGlobalVar(methodInstance, false);
  10017. }
  10018. BfIRType returnType;
  10019. SizedArray<BfIRType, 8> paramTypes;
  10020. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  10021. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  10022. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  10023. auto callingConv = GetIRCallingConvention(methodInstance);
  10024. if (callingConv != BfIRCallingConv_CDecl)
  10025. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  10026. SetupIRMethod(methodInstance, func, isInlined);
  10027. // auto srcModule = methodInstance->GetOwner()->GetModule();
  10028. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  10029. // {
  10030. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  10031. // {
  10032. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  10033. // }
  10034. // }
  10035. return func;
  10036. }
  10037. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  10038. {
  10039. if (assertName != NULL)
  10040. {
  10041. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  10042. }
  10043. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  10044. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  10045. return BfModuleMethodInstance();
  10046. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  10047. BfMethodDef* methodDef = NULL;
  10048. BfTypeInstance* foreignType = NULL;
  10049. if (methodInstance != NULL)
  10050. {
  10051. methodDef = methodInstance->mMethodDef;
  10052. if (methodInstance->mMethodInfoEx != NULL)
  10053. foreignType = methodInstance->mMethodInfoEx->mForeignType;
  10054. }
  10055. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  10056. {
  10057. // Can't use it, not reified
  10058. methodInstance = NULL;
  10059. }
  10060. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  10061. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  10062. {
  10063. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  10064. return BfModuleMethodInstance(methodInstance, func);
  10065. }
  10066. if (foreignType != NULL)
  10067. return GetMethodInstance(typeInstance, methodDef, BfTypeVector(), (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef), foreignType);
  10068. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  10069. }
  10070. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  10071. {
  10072. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  10073. while (typeInstance != NULL)
  10074. {
  10075. typeInstance->mTypeDef->PopulateMemberSets();
  10076. BfMemberSetEntry* entry = NULL;
  10077. BfMethodDef* methodDef = NULL;
  10078. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10079. methodDef = (BfMethodDef*)entry->mMemberDef;
  10080. while (methodDef != NULL)
  10081. {
  10082. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  10083. (methodDef->mGenericParams.size() == 0) &&
  10084. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  10085. {
  10086. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  10087. if (moduleMethodInstance)
  10088. return moduleMethodInstance;
  10089. }
  10090. methodDef = methodDef->mNextWithSameName;
  10091. }
  10092. if (!checkBase)
  10093. break;
  10094. typeInstance = typeInstance->mBaseType;
  10095. }
  10096. return BfModuleMethodInstance();
  10097. }
  10098. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  10099. {
  10100. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  10101. while (typeInstance != NULL)
  10102. {
  10103. typeInstance->mTypeDef->PopulateMemberSets();
  10104. BfMemberSetEntry* entry = NULL;
  10105. BfMethodDef* methodDef = NULL;
  10106. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10107. methodDef = (BfMethodDef*)entry->mMemberDef;
  10108. while (methodDef != NULL)
  10109. {
  10110. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  10111. (methodDef->mGenericParams.size() == 0) &&
  10112. (paramTypes.size() == methodDef->mParams.size()))
  10113. {
  10114. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  10115. if (moduleMethodInstance.mMethodInstance != NULL)
  10116. {
  10117. bool matches = true;
  10118. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  10119. {
  10120. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  10121. matches = false;
  10122. }
  10123. if (matches)
  10124. return moduleMethodInstance;
  10125. }
  10126. }
  10127. methodDef = methodDef->mNextWithSameName;
  10128. }
  10129. if (!checkBase)
  10130. break;
  10131. typeInstance = typeInstance->mBaseType;
  10132. }
  10133. return BfModuleMethodInstance();
  10134. }
  10135. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  10136. {
  10137. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  10138. PopulateType(internalType);
  10139. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  10140. if (!moduleMethodInstance)
  10141. {
  10142. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  10143. }
  10144. return moduleMethodInstance;
  10145. }
  10146. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  10147. {
  10148. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  10149. typeInstance->mOperatorInfo.Add(NULL);
  10150. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  10151. {
  10152. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  10153. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  10154. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  10155. BfTypeState typeState;
  10156. typeState.mType = typeInstance;
  10157. typeState.mCurTypeDef = operatorDef->mDeclaringType;
  10158. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  10159. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  10160. if (operatorDef->mReturnTypeRef != NULL)
  10161. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  10162. if (operatorDef->mParams.size() >= 1)
  10163. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  10164. if (operatorDef->mParams.size() >= 2)
  10165. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  10166. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  10167. }
  10168. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  10169. }
  10170. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  10171. {
  10172. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  10173. if (operatorInfo == NULL)
  10174. return NULL;
  10175. if (operatorInfo->mReturnType == NULL)
  10176. return NULL;
  10177. auto castFlags = BfCastFlags_IsConstraintCheck;
  10178. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  10179. castFlags = (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator);
  10180. if (lhs)
  10181. {
  10182. if (operatorInfo->mLHSType == NULL)
  10183. return NULL;
  10184. if (!CanCast(lhs, operatorInfo->mLHSType, castFlags))
  10185. return NULL;
  10186. }
  10187. if (rhs)
  10188. {
  10189. if (operatorInfo->mRHSType == NULL)
  10190. return NULL;
  10191. if (!CanCast(rhs, operatorInfo->mRHSType, castFlags))
  10192. return NULL;
  10193. }
  10194. return operatorInfo->mReturnType;
  10195. }
  10196. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  10197. {
  10198. while (typeInstance != NULL)
  10199. {
  10200. typeInstance->mTypeDef->PopulateMemberSets();
  10201. BfMemberSetEntry* entry = NULL;
  10202. BfMethodDef* methodDef = NULL;
  10203. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10204. methodDef = (BfMethodDef*)entry->mMemberDef;
  10205. while (methodDef != NULL)
  10206. {
  10207. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  10208. (methodDef->mGenericParams.size() == 0) &&
  10209. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  10210. {
  10211. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  10212. if (!methodInstanceGroup.IsImplemented())
  10213. return false;
  10214. if (methodInstanceGroup.mDefault == NULL)
  10215. return false;
  10216. return methodInstanceGroup.mDefault->mIsReified;
  10217. }
  10218. methodDef = methodDef->mNextWithSameName;
  10219. }
  10220. if (!checkBase)
  10221. break;
  10222. typeInstance = typeInstance->mBaseType;
  10223. }
  10224. return false;
  10225. }
  10226. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  10227. {
  10228. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  10229. while (typeInstance != NULL)
  10230. {
  10231. typeInstance->mTypeDef->PopulateMemberSets();
  10232. BfMemberSetEntry* entry = NULL;
  10233. BfMethodDef* methodDef = NULL;
  10234. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10235. methodDef = (BfMethodDef*)entry->mMemberDef;
  10236. while (methodDef != NULL)
  10237. {
  10238. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  10239. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  10240. return true;
  10241. methodDef = methodDef->mNextWithSameName;
  10242. }
  10243. if (!checkBase)
  10244. break;
  10245. typeInstance = typeInstance->mBaseType;
  10246. }
  10247. return BfModuleMethodInstance();
  10248. }
  10249. String BfModule::FieldToString(BfFieldInstance* fieldInstance)
  10250. {
  10251. auto result = TypeToString(fieldInstance->mOwner);
  10252. result += ".";
  10253. auto fieldDef = fieldInstance->GetFieldDef();
  10254. if (fieldDef != NULL)
  10255. result += fieldDef->mName;
  10256. else
  10257. result += "???";
  10258. return result;
  10259. }
  10260. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* typeGenericArgs, BfTypeVector* methodGenericArgs)
  10261. {
  10262. auto methodDef = methodInst->mMethodDef;
  10263. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  10264. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10265. bool hasGenericArgs = (typeGenericArgs != NULL) || (methodGenericArgs != NULL);
  10266. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  10267. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  10268. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  10269. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  10270. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10271. if (allowResolveGenericParamNames)
  10272. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10273. StringT<128> methodName;
  10274. auto _AddTypeName = [&](BfType* type)
  10275. {
  10276. auto typeNameFlags = BfTypeNameFlags_None;
  10277. if (allowResolveGenericParamNames)
  10278. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10279. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  10280. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  10281. methodName += TypeToString(type, typeNameFlags);
  10282. };
  10283. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  10284. {
  10285. _AddTypeName(methodInst->mReturnType);
  10286. methodName += " ";
  10287. }
  10288. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  10289. {
  10290. methodName += TypeToString(type, typeNameFlags);
  10291. if (methodName == "$")
  10292. methodName = "";
  10293. else if (!methodName.IsEmpty())
  10294. methodName += ".";
  10295. }
  10296. String accessorString;
  10297. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  10298. if (methodInst->mMethodDef->mIsLocalMethod)
  10299. {
  10300. int atPos = (int)methodDefName.IndexOf('$');
  10301. methodDefName.RemoveToEnd(atPos);
  10302. methodDefName.Replace("@", ".");
  10303. }
  10304. else
  10305. {
  10306. int atPos = (int)methodDefName.IndexOf('$');
  10307. if (atPos != -1)
  10308. {
  10309. accessorString = methodDefName.Substring(0, atPos);
  10310. if ((accessorString == "get") || (accessorString == "set"))
  10311. {
  10312. methodDefName = methodDefName.Substring(atPos + 1);
  10313. }
  10314. else
  10315. accessorString = "";
  10316. }
  10317. }
  10318. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  10319. {
  10320. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10321. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10322. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10323. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  10324. methodName += ".";
  10325. }
  10326. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  10327. {
  10328. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10329. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10330. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10331. methodName += "[";
  10332. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  10333. methodName += "].";
  10334. }
  10335. if (methodDef->mMethodType == BfMethodType_Operator)
  10336. {
  10337. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  10338. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  10339. {
  10340. // Don't add explicit/implicit part, since that's not available in GCC mangling
  10341. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  10342. {
  10343. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  10344. methodName += "explicit ";
  10345. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  10346. methodName += "explicit ";
  10347. }*/
  10348. methodName += "operator ";
  10349. if (methodInst->mReturnType != NULL)
  10350. methodName += TypeToString(methodInst->mReturnType);
  10351. }
  10352. else
  10353. {
  10354. methodName += "operator";
  10355. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  10356. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  10357. }
  10358. }
  10359. else if (methodDef->mMethodType == BfMethodType_Ctor)
  10360. {
  10361. if (methodDef->mIsStatic)
  10362. methodName += "__BfStaticCtor";
  10363. else
  10364. methodName += "this";
  10365. accessorString = "";
  10366. }
  10367. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  10368. {
  10369. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10370. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10371. {
  10372. methodName += "get indexer";
  10373. }
  10374. else
  10375. {
  10376. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10377. propertyDecl->mNameNode->ToString(methodName);
  10378. methodName += " get accessor";
  10379. return methodName;
  10380. }
  10381. }
  10382. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10383. {
  10384. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10385. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10386. {
  10387. methodName += "set indexer";
  10388. }
  10389. else
  10390. {
  10391. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10392. propertyDecl->mNameNode->ToString(methodName);
  10393. methodName += " set accessor";
  10394. return methodName;
  10395. }
  10396. }
  10397. else
  10398. methodName += methodDefName;
  10399. if (methodDef->mMethodType == BfMethodType_Mixin)
  10400. methodName += "!";
  10401. BfTypeVector newMethodGenericArgs;
  10402. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  10403. {
  10404. methodName += "<";
  10405. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  10406. {
  10407. if (i > 0)
  10408. methodName += ", ";
  10409. BfTypeNameFlags typeNameFlags = BfTypeNameFlag_ShortConst;
  10410. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  10411. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10412. if (allowResolveGenericParamNames)
  10413. typeNameFlags = (BfTypeNameFlags)(typeNameFlags | BfTypeNameFlag_ResolveGenericParamNames);
  10414. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  10415. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  10416. {
  10417. bool hasEmpty = false;
  10418. for (auto arg : *methodGenericArgs)
  10419. {
  10420. if (arg == NULL)
  10421. hasEmpty = true;
  10422. }
  10423. if (hasEmpty)
  10424. {
  10425. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  10426. {
  10427. auto arg = (*methodGenericArgs)[genericIdx];
  10428. if (arg != NULL)
  10429. newMethodGenericArgs.push_back(arg);
  10430. else
  10431. {
  10432. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  10433. if (genericParamInst->mTypeConstraint != NULL)
  10434. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  10435. else
  10436. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  10437. }
  10438. }
  10439. methodGenericArgs = &newMethodGenericArgs;
  10440. }
  10441. if (type->IsUnspecializedType())
  10442. type = ResolveGenericType(type, NULL, methodGenericArgs, mCurTypeInstance);
  10443. }
  10444. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  10445. {
  10446. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  10447. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  10448. methodName += TypeToString(type, typeNameFlags);
  10449. }
  10450. else
  10451. methodName += TypeToString(type, typeNameFlags);
  10452. }
  10453. methodName += ">";
  10454. }
  10455. if (accessorString.length() == 0)
  10456. {
  10457. int dispParamIdx = 0;
  10458. methodName += "(";
  10459. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  10460. {
  10461. int paramKind = methodInst->GetParamKind(paramIdx);
  10462. if ((paramKind == BfParamKind_ImplicitCapture) || (paramKind == BfParamKind_AppendIdx))
  10463. continue;
  10464. if (dispParamIdx > 0)
  10465. methodName += ", ";
  10466. if (paramKind == BfParamKind_Params)
  10467. methodName += "params ";
  10468. BfType* type = methodInst->GetParamType(paramIdx);
  10469. _AddTypeName(type);
  10470. methodName += " ";
  10471. methodName += methodInst->GetParamName(paramIdx);
  10472. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  10473. if ((paramInitializer != NULL) && ((methodNameFlags & BfMethodNameFlag_NoAst) == 0))
  10474. {
  10475. methodName += " = ";
  10476. methodName += paramInitializer->ToString();
  10477. }
  10478. dispParamIdx++;
  10479. }
  10480. methodName += ")";
  10481. }
  10482. if (accessorString.length() != 0)
  10483. {
  10484. methodName += " ";
  10485. methodName += accessorString;
  10486. }
  10487. if ((methodNameFlags & BfMethodNameFlag_IncludeMut) != 0)
  10488. {
  10489. if ((methodDef->mIsMutating) && (methodInst->GetOwner()->IsValueType()))
  10490. methodName += " mut";
  10491. }
  10492. return methodName;
  10493. }
  10494. void BfModule::pt(BfType* type)
  10495. {
  10496. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  10497. }
  10498. void BfModule::pm(BfMethodInstance* type)
  10499. {
  10500. OutputDebugStrF("%s\n", MethodToString(type).c_str());
  10501. }
  10502. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  10503. {
  10504. if ((flagsLeft & checkFlag) == 0)
  10505. return;
  10506. if (!str.empty())
  10507. {
  10508. if (flagsLeft == checkFlag)
  10509. {
  10510. if ((int)str.IndexOf(',') != -1)
  10511. str += ", and ";
  10512. else
  10513. str += " and ";
  10514. }
  10515. else
  10516. str += ", ";
  10517. }
  10518. str += addString;
  10519. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  10520. }
  10521. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  10522. {
  10523. String resultStr;
  10524. auto flagsLeft = attrTarget;
  10525. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  10526. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  10527. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  10528. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  10529. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  10530. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  10531. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  10532. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  10533. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  10534. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  10535. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  10536. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  10537. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  10538. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  10539. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  10540. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  10541. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  10542. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  10543. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  10544. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  10545. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  10546. if (resultStr.IsEmpty())
  10547. return "<nothing>";
  10548. return resultStr;
  10549. }
  10550. BfIRType BfModule::CurrentAddToConstHolder(BfIRType irType)
  10551. {
  10552. if (irType.mKind == BfIRTypeData::TypeKind_SizedArray)
  10553. {
  10554. auto sizedArrayType = (BfConstantSizedArrayType*)mBfIRBuilder->GetConstantById(irType.mId);
  10555. return mCurTypeInstance->GetOrCreateConstHolder()->GetSizedArrayType(CurrentAddToConstHolder(sizedArrayType->mType), (int)sizedArrayType->mLength);
  10556. }
  10557. return irType;
  10558. }
  10559. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  10560. {
  10561. auto constant = mBfIRBuilder->GetConstant(irVal);
  10562. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  10563. if (stringPoolIdx != -1)
  10564. {
  10565. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  10566. return;
  10567. }
  10568. if (constant->mConstType == BfConstType_Agg)
  10569. {
  10570. auto constArray = (BfConstantAgg*)constant;
  10571. SizedArray<BfIRValue, 8> newVals;
  10572. for (auto val : constArray->mValues)
  10573. {
  10574. auto newVal = val;
  10575. CurrentAddToConstHolder(newVal);
  10576. newVals.push_back(newVal);
  10577. }
  10578. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstAgg(CurrentAddToConstHolder(constArray->mType), newVals);
  10579. return;
  10580. }
  10581. auto origConst = irVal;
  10582. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10583. {
  10584. auto bitcast = (BfConstantBitCast*)constant;
  10585. BfIRValue newVal;
  10586. if (constant->mConstType == BfConstType_BitCast)
  10587. {
  10588. newVal = BfIRValue(BfIRValueFlags_Const, bitcast->mTarget);
  10589. CurrentAddToConstHolder(newVal);
  10590. }
  10591. else
  10592. newVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstNull();
  10593. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstBitCast(newVal, CurrentAddToConstHolder(bitcast->mToType));
  10594. return;
  10595. }
  10596. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  10597. }
  10598. void BfModule::ClearConstData()
  10599. {
  10600. mBfIRBuilder->ClearConstData();
  10601. mStringObjectPool.Clear();
  10602. mStringCharPtrPool.Clear();
  10603. mStringPoolRefs.Clear();
  10604. mUnreifiedStringPoolRefs.Clear();
  10605. mStaticFieldRefs.Clear();
  10606. }
  10607. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  10608. {
  10609. switch (constant->mTypeCode)
  10610. {
  10611. case BfTypeCode_StringId:
  10612. case BfTypeCode_Boolean:
  10613. case BfTypeCode_Int8:
  10614. case BfTypeCode_UInt8:
  10615. case BfTypeCode_Int16:
  10616. case BfTypeCode_UInt16:
  10617. case BfTypeCode_Int32:
  10618. case BfTypeCode_UInt32:
  10619. case BfTypeCode_Int64:
  10620. case BfTypeCode_UInt64:
  10621. case BfTypeCode_IntPtr:
  10622. case BfTypeCode_UIntPtr:
  10623. case BfTypeCode_IntUnknown:
  10624. case BfTypeCode_UIntUnknown:
  10625. case BfTypeCode_Char8:
  10626. case BfTypeCode_Char16:
  10627. case BfTypeCode_Char32:
  10628. case BfTypeCode_Float:
  10629. case BfTypeCode_Double:
  10630. {
  10631. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10632. BfTypedValue typedValue;
  10633. bool allowUnactualized = mBfIRBuilder->mIgnoreWrites;
  10634. if (constant->mTypeCode == BfTypeCode_StringId)
  10635. {
  10636. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10637. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10638. {
  10639. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType, allowUnactualized), wantType);
  10640. return typedValue;
  10641. }
  10642. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  10643. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType, allowUnactualized), stringType);
  10644. }
  10645. if (!typedValue)
  10646. {
  10647. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10648. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  10649. }
  10650. if (typedValue.mType == wantType)
  10651. return typedValue;
  10652. if (wantType->IsTypedPrimitive())
  10653. {
  10654. if (typedValue.mType == wantType->GetUnderlyingType())
  10655. {
  10656. typedValue.mType = wantType;
  10657. return typedValue;
  10658. }
  10659. }
  10660. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  10661. if (!castedTypedValue)
  10662. return BfTypedValue();
  10663. return castedTypedValue;
  10664. }
  10665. break;
  10666. default: break;
  10667. }
  10668. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  10669. BF_ASSERT(irValue);
  10670. if (!irValue)
  10671. return BfTypedValue();
  10672. if (constant->mConstType == BfConstType_GlobalVar)
  10673. {
  10674. mBfIRBuilder->PopulateType(wantType);
  10675. auto result = BfTypedValue(irValue, wantType, true);
  10676. if (!wantType->IsComposite())
  10677. result = LoadValue(result);
  10678. return result;
  10679. }
  10680. return BfTypedValue(irValue, wantType, false);
  10681. }
  10682. bool BfModule::HasUnactializedConstant(BfConstant* constant, BfIRConstHolder* constHolder)
  10683. {
  10684. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  10685. return true;
  10686. if (constant->mTypeCode == BfTypeCode_StringId)
  10687. return true;
  10688. if (constant->mTypeCode == BfTypeCode_CharPtr)
  10689. return true;
  10690. if (constant->mConstType == BfConstType_Agg)
  10691. {
  10692. auto constArray = (BfConstantAgg*)constant;
  10693. for (auto val : constArray->mValues)
  10694. {
  10695. if (HasUnactializedConstant(constHolder->GetConstant(val), constHolder))
  10696. return true;
  10697. }
  10698. }
  10699. if (constant->mConstType == BfConstType_PtrToInt)
  10700. {
  10701. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  10702. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10703. return HasUnactializedConstant(fromTarget, constHolder);
  10704. }
  10705. if (constant->mConstType == BfConstType_BitCast)
  10706. {
  10707. auto bitcast = (BfConstantBitCast*)constant;
  10708. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  10709. return HasUnactializedConstant(fromTarget, constHolder);
  10710. }
  10711. return false;
  10712. }
  10713. bool BfModule::HasGlobalVarReference(BfConstant* constant, BfIRConstHolder* constHolder)
  10714. {
  10715. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  10716. return true;
  10717. if (constant->mTypeCode == BfTypeCode_StringId)
  10718. return true;
  10719. if (constant->mConstType == BfConstType_GlobalVar)
  10720. return true;
  10721. // NullPtr is stand-in for GlobalVar during autocomplete
  10722. if (constant->mTypeCode == BfTypeCode_NullPtr)
  10723. return true;
  10724. if (constant->mConstType == BfConstType_Agg)
  10725. {
  10726. auto constArray = (BfConstantAgg*)constant;
  10727. for (auto val : constArray->mValues)
  10728. {
  10729. if (HasGlobalVarReference(constHolder->GetConstant(val), constHolder))
  10730. return true;
  10731. }
  10732. }
  10733. return false;
  10734. }
  10735. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType, bool allowUnactualized)
  10736. {
  10737. if (constant->mTypeCode == BfTypeCode_NullPtr)
  10738. {
  10739. if ((wantType == NULL) && (constant->mIRType.mKind == BfIRTypeData::TypeKind_TypeId))
  10740. wantType = mContext->mTypes[constant->mIRType.mId];
  10741. if (wantType == NULL)
  10742. return mBfIRBuilder->CreateConstNull();
  10743. return GetDefaultValue(wantType);
  10744. }
  10745. if ((constant->mTypeCode == BfTypeCode_StringId) || (constant->mTypeCode == BfTypeCode_CharPtr))
  10746. {
  10747. if (!allowUnactualized)
  10748. {
  10749. if ((wantType == NULL) ||
  10750. (wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10751. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10752. {
  10753. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  10754. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  10755. bool wantCharPtr = ((wantType != NULL) && (wantType->IsPointer()));
  10756. if ((wantType == NULL) && (constant->mTypeCode == BfTypeCode_CharPtr))
  10757. wantCharPtr = true;
  10758. if (wantCharPtr)
  10759. return GetStringCharPtr(stringObjConst, true);
  10760. return stringObjConst;
  10761. }
  10762. }
  10763. }
  10764. if (constant->mTypeCode == BfTypeCode_CharPtr)
  10765. {
  10766. if (!allowUnactualized)
  10767. {
  10768. if ((wantType == NULL) ||
  10769. (wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10770. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10771. {
  10772. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  10773. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  10774. if ((wantType != NULL) && (wantType->IsPointer()))
  10775. return GetStringCharPtr(stringObjConst, true);
  10776. return stringObjConst;
  10777. }
  10778. }
  10779. }
  10780. if (constant->mConstType == Beefy::BfConstType_TypeOf)
  10781. {
  10782. auto constTypeOf = (BfTypeOf_Const*)constant;
  10783. if (mCurTypeInstance != NULL)
  10784. AddDependency(constTypeOf->mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10785. return CreateTypeDataRef(constTypeOf->mType, true);
  10786. }
  10787. if (constant->mConstType == BfConstType_PtrToInt)
  10788. {
  10789. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  10790. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10791. return mBfIRBuilder->CreatePtrToInt(ConstantToCurrent(fromTarget, constHolder, NULL), fromPtrToInt->mToTypeCode);
  10792. }
  10793. if (constant->mConstType == BfConstType_IntToPtr)
  10794. {
  10795. auto fromPtrToInt = (BfConstantIntToPtr*)constant;
  10796. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10797. BfIRType toIRType = fromPtrToInt->mToType;
  10798. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10799. {
  10800. auto toType = mContext->mTypes[toIRType.mId];
  10801. toIRType = mBfIRBuilder->MapType(toType);
  10802. }
  10803. return mBfIRBuilder->CreateIntToPtr(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10804. }
  10805. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10806. {
  10807. auto bitcast = (BfConstantBitCast*)constant;
  10808. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  10809. BfIRType toIRType = bitcast->mToType;
  10810. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10811. {
  10812. auto toType = mContext->mTypes[toIRType.mId];
  10813. toIRType = mBfIRBuilder->MapType(toType);
  10814. }
  10815. return mBfIRBuilder->CreateBitCast(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10816. }
  10817. if (constant->mConstType == BfConstType_Agg)
  10818. {
  10819. auto constArray = (BfConstantAgg*)constant;
  10820. if ((wantType == NULL) && (constArray->mType.mKind == BfIRTypeData::TypeKind_TypeId))
  10821. wantType = mContext->mTypes[constArray->mType.mId];
  10822. if (wantType->IsArray())
  10823. wantType = CreateSizedArrayType(wantType->GetUnderlyingType(), (int)constArray->mValues.mSize);
  10824. bool handleAsArray = false;
  10825. SizedArray<BfIRValue, 8> newVals;
  10826. if (wantType->IsSizedArray())
  10827. {
  10828. handleAsArray = true;
  10829. }
  10830. else if (wantType->IsInstanceOf(mCompiler->mSpanTypeDef))
  10831. {
  10832. auto valueType = ResolveTypeDef(mCompiler->mValueTypeTypeDef);
  10833. handleAsArray = true;
  10834. if (!constArray->mValues.IsEmpty())
  10835. {
  10836. auto firstConstant = constHolder->GetConstant(constArray->mValues[0]);
  10837. if ((firstConstant->mConstType == BfConstType_AggZero) && (firstConstant->mIRType.mKind == BfIRType::TypeKind_TypeId) &&
  10838. (firstConstant->mIRType.mId == valueType->mTypeId))
  10839. handleAsArray = false;
  10840. if (firstConstant->mConstType == BfConstType_Agg)
  10841. {
  10842. auto firstConstArray = (BfConstantAgg*)firstConstant;
  10843. if ((firstConstArray->mType.mKind == BfIRType::TypeKind_TypeId) &&
  10844. (firstConstArray->mType.mId == valueType->mTypeId))
  10845. handleAsArray = false;
  10846. }
  10847. }
  10848. }
  10849. if (handleAsArray)
  10850. {
  10851. auto elementType = wantType->GetUnderlyingType();
  10852. for (auto val : constArray->mValues)
  10853. {
  10854. newVals.Add(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  10855. }
  10856. }
  10857. else
  10858. {
  10859. auto wantTypeInst = wantType->ToTypeInstance();
  10860. if (wantTypeInst == NULL)
  10861. {
  10862. InternalError("BfModule::ConstantToCurrent typeInst error");
  10863. return BfIRValue();
  10864. }
  10865. if (wantTypeInst->mBaseType != NULL)
  10866. {
  10867. auto baseVal = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[0]), constHolder, wantTypeInst->mBaseType);
  10868. newVals.Add(baseVal);
  10869. }
  10870. if (wantType->IsUnion())
  10871. {
  10872. auto innerType = wantType->ToTypeInstance()->GetUnionInnerType();
  10873. if (!innerType->IsValuelessType())
  10874. {
  10875. auto val = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[1]), constHolder, innerType);
  10876. newVals.Add(val);
  10877. }
  10878. }
  10879. if ((!wantType->IsUnion()) || (wantType->IsPayloadEnum()))
  10880. {
  10881. for (auto& fieldInstance : wantTypeInst->mFieldInstances)
  10882. {
  10883. if (fieldInstance.mDataIdx < 0)
  10884. continue;
  10885. if (fieldInstance.mDataIdx >= constArray->mValues.mSize)
  10886. {
  10887. InternalError("BfModule::ConstantToCurrent union error");
  10888. return BfIRValue();
  10889. }
  10890. auto val = constArray->mValues[fieldInstance.mDataIdx];
  10891. BfIRValue memberVal = ConstantToCurrent(constHolder->GetConstant(val), constHolder, fieldInstance.mResolvedType);
  10892. if (fieldInstance.mDataIdx == newVals.mSize)
  10893. newVals.Add(memberVal);
  10894. else
  10895. {
  10896. while (fieldInstance.mDataIdx >= newVals.mSize)
  10897. newVals.Add(BfIRValue());
  10898. newVals[fieldInstance.mDataIdx] = memberVal;
  10899. }
  10900. }
  10901. }
  10902. for (auto& val : newVals)
  10903. {
  10904. if (!val)
  10905. val = mBfIRBuilder->CreateConstArrayZero(0);
  10906. }
  10907. }
  10908. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(wantType, BfIRPopulateType_Identity), newVals);
  10909. }
  10910. return mBfIRBuilder->CreateConst(constant, constHolder);
  10911. }
  10912. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget, bool force)
  10913. {
  10914. if (attrTarget == BfAttributeTargets_SkipValidate)
  10915. return;
  10916. for (auto& customAttribute : customAttributes->mAttributes)
  10917. {
  10918. if (!customAttribute.mAwaitingValidation)
  10919. continue;
  10920. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  10921. {
  10922. if ((customAttribute.mIsMultiUse) && (!force))
  10923. continue;
  10924. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  10925. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  10926. }
  10927. customAttribute.mAwaitingValidation = false;
  10928. }
  10929. }
  10930. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10931. {
  10932. bool allowNonConstArgs = (flags & BfGetCustomAttributesFlags_AllowNonConstArgs) != 0;
  10933. bool keepConstsInModule = (flags & BfGetCustomAttributesFlags_KeepConstsInModule) != 0;
  10934. if (!mCompiler->mHasRequiredTypes)
  10935. return;
  10936. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  10937. {
  10938. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  10939. sourceClassifier->VisitChild(attributesDirective);
  10940. }
  10941. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  10942. if (mCompiler->IsAutocomplete())
  10943. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  10944. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  10945. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  10946. BfTypeDef* activeTypeDef = GetActiveTypeDef();
  10947. BfAutoComplete* autoComplete = NULL;
  10948. if (mCompiler->mResolvePassData != NULL)
  10949. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  10950. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  10951. {
  10952. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  10953. {
  10954. if (captureInfo == NULL)
  10955. {
  10956. Fail("Capture specifiers can only be used in lambda allocations", tokenNode);
  10957. continue;
  10958. }
  10959. BfCaptureInfo::Entry captureEntry;
  10960. captureEntry.mRefNode = tokenNode;
  10961. captureEntry.mCaptureType = BfCaptureType_Copy;
  10962. if (tokenNode->mToken == BfToken_Ampersand)
  10963. captureEntry.mCaptureType = BfCaptureType_Reference;
  10964. if (tokenNode->mToken == BfToken_Question)
  10965. captureEntry.mCaptureType = BfCaptureType_Auto;
  10966. if (!attributesDirective->mArguments.IsEmpty())
  10967. {
  10968. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]))
  10969. captureEntry.mNameNode = identifierNode;
  10970. else if (auto thisExpr = BfNodeDynCast<BfThisExpression>(attributesDirective->mArguments[0]))
  10971. {
  10972. captureEntry.mNameNode = thisExpr;
  10973. }
  10974. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  10975. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  10976. }
  10977. captureInfo->mCaptures.Add(captureEntry);
  10978. continue;
  10979. }
  10980. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  10981. BfCustomAttribute customAttribute;
  10982. customAttribute.mAwaitingValidation = true;
  10983. customAttribute.mDeclaringType = activeTypeDef;
  10984. customAttribute.mRef = attributesDirective;
  10985. customAttribute.mIsMultiUse = attributesDirective->mIsMultiUse;
  10986. if (attributesDirective->mAttrOpenToken != NULL)
  10987. targetOverride = (BfAttributeTargets)0;
  10988. if (attributesDirective->mAttributeTypeRef == NULL)
  10989. {
  10990. AssertErrorState();
  10991. continue;
  10992. }
  10993. BfType* attrType;
  10994. if (mContext->mCurTypeState != NULL)
  10995. {
  10996. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10997. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10998. }
  10999. else
  11000. {
  11001. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  11002. }
  11003. BfTypeDef* attrTypeDef = NULL;
  11004. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  11005. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  11006. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  11007. {
  11008. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  11009. if (attrTypeDef != NULL)
  11010. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  11011. }
  11012. bool isBypassedAttr = false;
  11013. if (attrTypeDef != NULL)
  11014. {
  11015. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  11016. // We solve it by having a 'bypass' for known attributes that Object depends on
  11017. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  11018. {
  11019. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  11020. {
  11021. for (auto methodDef : attrTypeDef->mMethods)
  11022. {
  11023. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  11024. {
  11025. customAttribute.mType = attrType->ToTypeInstance();
  11026. customAttribute.mCtor = methodDef;
  11027. isBypassedAttr = true;
  11028. break;
  11029. }
  11030. }
  11031. }
  11032. }
  11033. if (isBypassedAttr)
  11034. {
  11035. customAttribute.mAwaitingValidation = false;
  11036. customAttributes->mAttributes.push_back(customAttribute);
  11037. continue;
  11038. }
  11039. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInst(mContext->mUnreifiedModule->mCurTypeInstance, mCurTypeInstance);
  11040. SetAndRestoreValue<BfMethodInstance*> prevCurMethodInst(mContext->mUnreifiedModule->mCurMethodInstance, mCurMethodInstance);
  11041. if (mContext->mCurTypeState != NULL)
  11042. {
  11043. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  11044. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  11045. }
  11046. else
  11047. {
  11048. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  11049. }
  11050. }
  11051. BfTypeInstance* attrTypeInst = NULL;
  11052. if (attrType == NULL)
  11053. continue;
  11054. attrTypeInst = attrType->ToTypeInstance();
  11055. if ((attrTypeInst != NULL) && (attrTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting))
  11056. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  11057. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  11058. {
  11059. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  11060. continue;
  11061. }
  11062. if ((mIsReified) && (attrTypeInst->mAttributeData != NULL) && ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_ReflectAttribute) != 0))
  11063. {
  11064. // Reify attribute
  11065. PopulateType(attrTypeInst);
  11066. }
  11067. if (mCurTypeInstance != NULL)
  11068. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  11069. customAttribute.mType = attrTypeInst;
  11070. bool allocatedMethodState = NULL;
  11071. defer(
  11072. {
  11073. if (allocatedMethodState)
  11074. {
  11075. delete mCurMethodState;
  11076. mCurMethodState = NULL;
  11077. }
  11078. });
  11079. if (mCurMethodState == NULL)
  11080. {
  11081. allocatedMethodState = true;
  11082. mCurMethodState = new BfMethodState();
  11083. mCurMethodState->mTempKind = BfMethodState::TempKind_Static;
  11084. }
  11085. BfConstResolver constResolver(this);
  11086. if (allowNonConstArgs)
  11087. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  11088. bool inPropSet = false;
  11089. SizedArray<BfResolvedArg, 2> argValues;
  11090. for (BfExpression* arg : attributesDirective->mArguments)
  11091. {
  11092. if (arg == NULL)
  11093. {
  11094. continue;
  11095. }
  11096. if (autoComplete != NULL)
  11097. autoComplete->mShowAttributeProperties = attrTypeInst;
  11098. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  11099. {
  11100. inPropSet = true;
  11101. if (autoComplete != NULL)
  11102. autoComplete->CheckNode(assignExpr->mLeft, true);
  11103. String findName = assignExpr->mLeft->ToString();
  11104. BfPropertyDef* bestProp = NULL;
  11105. BfTypeInstance* bestPropTypeInst = NULL;
  11106. BfFieldDef* bestField = NULL;
  11107. BfTypeInstance* bestFieldTypeInst = NULL;
  11108. auto checkTypeInst = attrTypeInst;
  11109. while (checkTypeInst != NULL)
  11110. {
  11111. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  11112. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  11113. {
  11114. if (prop->mName == findName)
  11115. {
  11116. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  11117. {
  11118. bestProp = prop;
  11119. bestPropTypeInst = checkTypeInst;
  11120. }
  11121. }
  11122. }
  11123. for (auto field : checkTypeInst->mTypeDef->mFields)
  11124. {
  11125. if (field->mName == findName)
  11126. {
  11127. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  11128. {
  11129. bestField = field;
  11130. bestFieldTypeInst = checkTypeInst;
  11131. }
  11132. }
  11133. }
  11134. if ((bestProp != NULL) || (bestField != NULL))
  11135. break;
  11136. checkTypeInst = checkTypeInst->mBaseType;
  11137. }
  11138. bool handledExpr = false;
  11139. if (bestField != NULL)
  11140. {
  11141. handledExpr = true;
  11142. if (mCompiler->mResolvePassData != NULL)
  11143. {
  11144. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  11145. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  11146. {
  11147. autoComplete->mDefField = bestField;
  11148. autoComplete->mDefType = attrTypeDef;
  11149. }
  11150. }
  11151. if (bestField->mProtection != BfProtection_Public)
  11152. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  11153. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  11154. BfCustomAttributeSetField setField;
  11155. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  11156. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  11157. if (assignExpr->mRight != NULL)
  11158. {
  11159. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType, BfConstResolveFlag_NoActualizeValues);
  11160. if (result)
  11161. {
  11162. if (!keepConstsInModule)
  11163. CurrentAddToConstHolder(result.mValue);
  11164. setField.mParam = result;
  11165. customAttribute.mSetField.push_back(setField);
  11166. }
  11167. }
  11168. }
  11169. else if (bestProp == NULL)
  11170. {
  11171. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  11172. }
  11173. else
  11174. {
  11175. BfMethodDef* setMethod = NULL;
  11176. for (auto methodDef : bestProp->mMethods)
  11177. {
  11178. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  11179. {
  11180. setMethod = methodDef;
  11181. break;
  11182. }
  11183. }
  11184. if (setMethod == NULL)
  11185. {
  11186. Fail("Property has no setter", assignExpr->mLeft);
  11187. }
  11188. else
  11189. {
  11190. if (mCompiler->mResolvePassData != NULL)
  11191. {
  11192. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  11193. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  11194. {
  11195. autoComplete->mDefProp = bestProp;
  11196. autoComplete->mDefType = attrTypeDef;
  11197. }
  11198. }
  11199. handledExpr = true;
  11200. if (bestProp->mProtection != BfProtection_Public)
  11201. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  11202. BfResolvedArg resolvedArg;
  11203. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  11204. BfCustomAttributeSetProperty setProperty;
  11205. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  11206. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  11207. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  11208. if (methodInstance.mMethodInstance != NULL)
  11209. {
  11210. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  11211. if (assignExpr->mRight != NULL)
  11212. {
  11213. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType, BfConstResolveFlag_NoActualizeValues);
  11214. if ((result) && (!result.mType->IsVar()))
  11215. {
  11216. if (!result.mValue.IsConst())
  11217. result = GetDefaultTypedValue(result.mType);
  11218. BF_ASSERT(result.mType == propType);
  11219. if (!keepConstsInModule)
  11220. CurrentAddToConstHolder(result.mValue);
  11221. setProperty.mParam = result;
  11222. customAttribute.mSetProperties.push_back(setProperty);
  11223. }
  11224. }
  11225. }
  11226. }
  11227. }
  11228. if ((!handledExpr) && (assignExpr->mRight != NULL))
  11229. constResolver.Resolve(assignExpr->mRight, NULL, BfConstResolveFlag_NoActualizeValues);
  11230. }
  11231. else
  11232. {
  11233. if (inPropSet)
  11234. {
  11235. Fail("Named attribute argument expected", arg); // CS1016
  11236. }
  11237. BfDeferEvalChecker deferEvalChecker;
  11238. arg->Accept(&deferEvalChecker);
  11239. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  11240. BfResolvedArg resolvedArg;
  11241. resolvedArg.mExpression = arg;
  11242. if (deferParamEval)
  11243. {
  11244. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  11245. }
  11246. else
  11247. resolvedArg.mTypedValue = constResolver.Resolve(arg, NULL, BfConstResolveFlag_NoActualizeValues);
  11248. if (!inPropSet)
  11249. {
  11250. argValues.push_back(resolvedArg);
  11251. }
  11252. }
  11253. if (autoComplete != NULL)
  11254. autoComplete->mShowAttributeProperties = NULL;
  11255. }
  11256. auto wasCapturingMethodInfo = false;
  11257. if (autoComplete != NULL)
  11258. {
  11259. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  11260. if (attributesDirective->mCtorOpenParen != NULL)
  11261. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  11262. }
  11263. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, BfMethodGenericArguments());
  11264. methodMatcher.mBfEvalExprFlags = constResolver.mBfEvalExprFlags;
  11265. attrTypeDef = attrTypeInst->mTypeDef;
  11266. bool success = true;
  11267. int methodCheckCount = 0;
  11268. bool isFailurePass = false;
  11269. for (int pass = 0; pass < 2; pass++)
  11270. {
  11271. bool isFailurePass = pass == 1;
  11272. for (auto checkMethod : attrTypeDef->mMethods)
  11273. {
  11274. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  11275. continue; // Don't match private default ctor if there's a user-defined one
  11276. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  11277. continue;
  11278. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  11279. continue;
  11280. methodCheckCount++;
  11281. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  11282. }
  11283. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  11284. break;
  11285. }
  11286. if (autoComplete != NULL)
  11287. {
  11288. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  11289. {
  11290. autoComplete->mIsCapturingMethodMatchInfo = true;
  11291. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  11292. }
  11293. else
  11294. autoComplete->mIsCapturingMethodMatchInfo = false;
  11295. }
  11296. if (methodMatcher.mBestMethodDef == NULL)
  11297. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  11298. if (methodMatcher.mBestMethodDef == NULL)
  11299. {
  11300. if (methodCheckCount == 0)
  11301. Fail(StrFormat("No attribute constructors found for type '%s'", TypeToString(attrTypeInst).c_str()), attributesDirective);
  11302. AssertErrorState();
  11303. continue;
  11304. }
  11305. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  11306. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  11307. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  11308. {
  11309. Fail("Custom attribute circular reference", attributesDirective);
  11310. }
  11311. if (mCurTypeInstance != NULL)
  11312. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  11313. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  11314. success = false;
  11315. for (auto& arg : argValues)
  11316. {
  11317. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  11318. {
  11319. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  11320. constResolver.Resolve(expr, NULL, BfConstResolveFlag_NoActualizeValues);
  11321. }
  11322. }
  11323. // Move all those to the constHolder
  11324. if (!keepConstsInModule)
  11325. {
  11326. for (auto& ctorArg : customAttribute.mCtorArgs)
  11327. {
  11328. if (ctorArg.IsConst())
  11329. CurrentAddToConstHolder(ctorArg);
  11330. }
  11331. }
  11332. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  11333. {
  11334. targetOverride = BfAttributeTargets_ReturnValue;
  11335. if (attrTarget != BfAttributeTargets_Method)
  11336. {
  11337. 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.",
  11338. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  11339. success = false;
  11340. }
  11341. }
  11342. if ((success) && (targetOverride != (BfAttributeTargets)0))
  11343. {
  11344. if ((mCurMethodInstance != NULL) && (targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  11345. {
  11346. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  11347. if (methodInfoEx->mMethodCustomAttributes == NULL)
  11348. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  11349. if (success)
  11350. {
  11351. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  11352. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  11353. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  11354. }
  11355. }
  11356. // Mark as failed since we don't actually want to add this to the custom attributes set
  11357. success = false;
  11358. }
  11359. if (success)
  11360. {
  11361. if ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_DisallowAllowMultiple) != 0)
  11362. {
  11363. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  11364. {
  11365. if (prevCustomAttribute.mType == attrTypeInst)
  11366. {
  11367. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToCleanAttributeString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  11368. }
  11369. }
  11370. }
  11371. }
  11372. if (success)
  11373. {
  11374. customAttributes->mAttributes.push_back(customAttribute);
  11375. }
  11376. }
  11377. ValidateCustomAttributes(customAttributes, attrTarget);
  11378. }
  11379. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  11380. {
  11381. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  11382. GetCustomAttributes(customAttributes, attributesDirective, attrType, flags, captureInfo);
  11383. return customAttributes;
  11384. }
  11385. BfCustomAttributes* BfModule::GetCustomAttributes(BfTypeDef* typeDef)
  11386. {
  11387. BF_ASSERT(mCompiler->IsAutocomplete());
  11388. BfAttributeTargets attrTarget;
  11389. if (typeDef->mIsDelegate)
  11390. attrTarget = BfAttributeTargets_Delegate;
  11391. else if (typeDef->mIsFunction)
  11392. attrTarget = BfAttributeTargets_Function;
  11393. else if (typeDef->mTypeCode == BfTypeCode_Enum)
  11394. attrTarget = BfAttributeTargets_Enum;
  11395. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  11396. attrTarget = BfAttributeTargets_Interface;
  11397. else if (typeDef->mTypeCode == BfTypeCode_Struct)
  11398. attrTarget = BfAttributeTargets_Struct;
  11399. else if (typeDef->mTypeCode == BfTypeCode_Extension)
  11400. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Struct | BfAttributeTargets_Class | BfAttributeTargets_Interface | BfAttributeTargets_Enum);
  11401. else
  11402. attrTarget = BfAttributeTargets_Class;
  11403. return GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  11404. }
  11405. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  11406. {
  11407. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  11408. Warn(0, "Unused attributes", attributeState->mSrc);
  11409. }
  11410. void BfModule::ProcessTypeInstCustomAttributes(int& packing, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  11411. {
  11412. if (mCurTypeInstance->mTypeDef->mIsAlwaysInclude)
  11413. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11414. if (mCurTypeInstance->mCustomAttributes != NULL)
  11415. {
  11416. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11417. {
  11418. String typeName = TypeToString(customAttribute.mType);
  11419. if (typeName == "System.PackedAttribute")
  11420. {
  11421. packing = 1;
  11422. if (customAttribute.mCtorArgs.size() >= 1)
  11423. {
  11424. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11425. int checkPacking = alignConstant->mInt32;
  11426. if (((checkPacking & (checkPacking - 1)) == 0) && (packing > 0) && (packing < 256))
  11427. packing = checkPacking;
  11428. else
  11429. Fail("Packing must be a power of 2", customAttribute.GetRefNode());
  11430. }
  11431. }
  11432. else if (typeName == "System.UnionAttribute")
  11433. {
  11434. isUnion = true;
  11435. }
  11436. else if (typeName == "System.CReprAttribute")
  11437. {
  11438. isCRepr = true;
  11439. isOrdered = true;
  11440. }
  11441. else if (typeName == "System.OrderedAttribute")
  11442. {
  11443. isOrdered = true;
  11444. }
  11445. else if (typeName == "System.AlwaysIncludeAttribute")
  11446. {
  11447. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11448. for (auto setProp : customAttribute.mSetProperties)
  11449. {
  11450. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  11451. if (propertyDef->mName == "AssumeInstantiated")
  11452. {
  11453. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11454. if ((constant != NULL) && (constant->mBool))
  11455. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_AssumeInstantiated);
  11456. }
  11457. else if (propertyDef->mName == "IncludeAllMethods")
  11458. {
  11459. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11460. if ((constant != NULL) && (constant->mBool))
  11461. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_IncludeAllMethods);
  11462. }
  11463. }
  11464. }
  11465. else if (typeName == "System.AlignAttribute")
  11466. {
  11467. if (customAttribute.mCtorArgs.size() >= 1)
  11468. {
  11469. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11470. int checkAlign = alignConstant->mInt32;
  11471. if ((checkAlign & (checkAlign - 1)) == 0)
  11472. alignOverride = checkAlign;
  11473. else
  11474. Fail("Alignment must be a power of 2", customAttribute.GetRefNode());
  11475. }
  11476. }
  11477. else if (typeName == "System.UnderlyingArrayAttribute")
  11478. {
  11479. if (customAttribute.mCtorArgs.size() >= 2)
  11480. {
  11481. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11482. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  11483. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  11484. {
  11485. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  11486. underlyingArraySize = sizeConstant->mInt32;
  11487. }
  11488. }
  11489. }
  11490. if (customAttribute.mType->mAttributeData == NULL)
  11491. PopulateType(customAttribute.mType);
  11492. BF_ASSERT(customAttribute.mType->mAttributeData != NULL);
  11493. if ((customAttribute.mType->mAttributeData != NULL) && ((customAttribute.mType->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0))
  11494. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | customAttribute.mType->mAttributeData->mAlwaysIncludeUser);
  11495. }
  11496. }
  11497. }
  11498. // Checking to see if we're an attribute or not
  11499. void BfModule::ProcessCustomAttributeData()
  11500. {
  11501. if (mCurTypeInstance->mAttributeData != NULL)
  11502. return;
  11503. bool isAttribute = false;
  11504. auto checkTypeInst = mCurTypeInstance->mBaseType;
  11505. while (checkTypeInst != NULL)
  11506. {
  11507. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  11508. isAttribute = true;
  11509. checkTypeInst = checkTypeInst->mBaseType;
  11510. }
  11511. if (!isAttribute)
  11512. return;
  11513. auto attributeData = new BfAttributeData();
  11514. bool hasCustomAttribute = false;
  11515. if (mCurTypeInstance->mCustomAttributes != NULL)
  11516. {
  11517. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11518. {
  11519. if (customAttribute.mType->IsInstanceOf(mCompiler->mAttributeUsageAttributeTypeDef))
  11520. {
  11521. if (customAttribute.mCtorArgs.size() > 0)
  11522. {
  11523. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11524. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11525. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11526. }
  11527. if (customAttribute.mCtorArgs.size() == 2)
  11528. {
  11529. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11530. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11531. {
  11532. attributeData->mFlags = (BfAttributeFlags)constant->mInt32;
  11533. }
  11534. }
  11535. for (auto& setProp : customAttribute.mSetProperties)
  11536. {
  11537. BfPropertyDef* propDef = setProp.mPropertyRef;
  11538. if (propDef->mName == "AllowMultiple")
  11539. {
  11540. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11541. if ((constant != NULL) && (constant->mBool))
  11542. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_DisallowAllowMultiple);
  11543. else
  11544. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_DisallowAllowMultiple);
  11545. }
  11546. else if (propDef->mName == "Inherited")
  11547. {
  11548. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11549. if ((constant != NULL) && (constant->mBool))
  11550. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_NotInherited);
  11551. else
  11552. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_NotInherited);
  11553. }
  11554. else if (propDef->mName == "ValidOn")
  11555. {
  11556. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11557. if (constant != NULL)
  11558. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11559. }
  11560. else if (propDef->mName == "AlwaysIncludeUser")
  11561. {
  11562. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11563. if (constant != NULL)
  11564. attributeData->mAlwaysIncludeUser = (BfAlwaysIncludeFlags)constant->mInt32;
  11565. }
  11566. }
  11567. hasCustomAttribute = true;
  11568. }
  11569. }
  11570. }
  11571. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  11572. {
  11573. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  11574. attributeData->mFlags = mCurTypeInstance->mBaseType->mAttributeData->mFlags;
  11575. attributeData->mAlwaysIncludeUser = mCurTypeInstance->mBaseType->mAttributeData->mAlwaysIncludeUser;
  11576. }
  11577. mCurTypeInstance->mAttributeData = attributeData;
  11578. }
  11579. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  11580. {
  11581. auto constant = constHolder->GetConstant(irValue);
  11582. if (constant == NULL)
  11583. return false;
  11584. if (constant->mTypeCode != BfTypeCode_StringId)
  11585. return false;
  11586. int stringId = constant->mInt32;
  11587. BfStringPoolEntry* entry = NULL;
  11588. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  11589. {
  11590. str += entry->mString;
  11591. }
  11592. else
  11593. {
  11594. BF_DBG_FATAL("Failed to find string by id");
  11595. }
  11596. return true;
  11597. }
  11598. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  11599. {
  11600. BfVariant variant;
  11601. variant.mTypeCode = BfTypeCode_None;
  11602. BfType* primType = NULL;
  11603. if (value.mType->IsPrimitiveType())
  11604. primType = (BfPrimitiveType*)value.mType;
  11605. else if (value.mType->IsTypedPrimitive())
  11606. primType = value.mType->GetUnderlyingType();
  11607. else if (value.mType->IsInstanceOf(mCompiler->mStringTypeDef))
  11608. primType = value.mType;
  11609. if (primType)
  11610. {
  11611. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  11612. if (constant != NULL)
  11613. {
  11614. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  11615. {
  11616. variant.mUInt64 = 0;
  11617. variant.mTypeCode = BfTypeCode_Let;
  11618. return variant;
  11619. }
  11620. if (constant->mConstType == BfConstType_GlobalVar)
  11621. {
  11622. int stringIdx = GetStringPoolIdx(value.mValue, mBfIRBuilder);
  11623. if (stringIdx != -1)
  11624. {
  11625. variant.mTypeCode = BfTypeCode_StringId;
  11626. variant.mInt64 = stringIdx;
  11627. return variant;
  11628. }
  11629. }
  11630. switch (constant->mTypeCode)
  11631. {
  11632. case BfTypeCode_Boolean:
  11633. case BfTypeCode_Int8:
  11634. case BfTypeCode_UInt8:
  11635. case BfTypeCode_Int16:
  11636. case BfTypeCode_UInt16:
  11637. case BfTypeCode_Int32:
  11638. case BfTypeCode_UInt32:
  11639. case BfTypeCode_Int64:
  11640. case BfTypeCode_UInt64:
  11641. case BfTypeCode_IntPtr:
  11642. case BfTypeCode_UIntPtr:
  11643. case BfTypeCode_IntUnknown:
  11644. case BfTypeCode_UIntUnknown:
  11645. case BfTypeCode_Double:
  11646. case BfTypeCode_Char8:
  11647. case BfTypeCode_Char16:
  11648. case BfTypeCode_Char32:
  11649. case BfTypeCode_StringId:
  11650. variant.mTypeCode = constant->mTypeCode;
  11651. if (((variant.mTypeCode == BfTypeCode_Int64) || (variant.mTypeCode == BfTypeCode_UInt64)) &&
  11652. (primType->mSize > 0) && (primType->mSize < 8) &&
  11653. (mBfIRBuilder->IsIntable(primType->GetTypeCode())))
  11654. {
  11655. // We may have an 'int unknown' that we need to downsize
  11656. variant.mTypeCode = primType->GetTypeCode();
  11657. }
  11658. variant.mInt64 = constant->mInt64;
  11659. break;
  11660. case BfTypeCode_Float:
  11661. variant.mTypeCode = constant->mTypeCode;
  11662. variant.mSingle = (float)constant->mDouble;
  11663. break;
  11664. default:
  11665. if (refNode != NULL)
  11666. Fail("Invalid const expression type", refNode);
  11667. break;
  11668. }
  11669. }
  11670. }
  11671. else if (value.mType->IsConstExprValue())
  11672. {
  11673. auto constExprType = (BfConstExprValueType*)value.mType;
  11674. return constExprType->mValue;
  11675. }
  11676. else if (value.mType->IsValueType())
  11677. {
  11678. PopulateType(value.mType);
  11679. int allocSize = value.mType->mSize + 4;
  11680. BfVariant::StructData* structData = (BfVariant::StructData*)(new uint8[allocSize]);
  11681. memset(structData, 0, allocSize);
  11682. structData->mSize = value.mType->mSize;
  11683. mBfIRBuilder->WriteConstant(value.mValue, structData->mData, value.mType);
  11684. variant.mTypeCode = BfTypeCode_Struct;
  11685. variant.mPtr = structData;
  11686. }
  11687. return variant;
  11688. }
  11689. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue, bool makeInReadOnly)
  11690. {
  11691. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  11692. {
  11693. auto refType = (BfRefType*)typedValue.mType;
  11694. auto elementType = typedValue.mType->GetUnderlyingType();
  11695. if (typedValue.IsAddr())
  11696. {
  11697. if (elementType->IsValuelessType())
  11698. {
  11699. BF_ASSERT(!typedValue.mValue);
  11700. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11701. }
  11702. else
  11703. typedValue = BfTypedValue(mBfIRBuilder->CreateAlignedLoad(typedValue.mValue, elementType->mAlign), elementType, true);
  11704. }
  11705. else
  11706. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11707. if (typedValue.mType->IsValuelessType())
  11708. {
  11709. BF_ASSERT(typedValue.mValue.IsFake());
  11710. }
  11711. if ((refType->mRefKind == BfRefType::RefKind_In) && (makeInReadOnly))
  11712. {
  11713. if (typedValue.mKind == BfTypedValueKind_Addr)
  11714. typedValue.mKind = BfTypedValueKind_ReadOnlyAddr;
  11715. }
  11716. }
  11717. return typedValue;
  11718. }
  11719. BfTypedValue BfModule::SanitizeAddr(BfTypedValue typedValue)
  11720. {
  11721. if (!typedValue)
  11722. return typedValue;
  11723. if (typedValue.mType->IsRef())
  11724. {
  11725. typedValue = LoadValue(typedValue);
  11726. auto copiedVal = BfTypedValue(CreateAlloca(typedValue.mType), typedValue.mType, true);
  11727. mBfIRBuilder->CreateStore(typedValue.mValue, copiedVal.mValue);
  11728. return copiedVal;
  11729. }
  11730. return typedValue;
  11731. }
  11732. BfTypedValue BfModule::ToRef(BfTypedValue typedValue, BfRefType* refType)
  11733. {
  11734. if (refType == NULL)
  11735. refType = CreateRefType(typedValue.mType);
  11736. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (typedValue.mType->IsObjectOrInterface()))
  11737. {
  11738. return LoadValue(typedValue);
  11739. }
  11740. if (refType->mRefKind == BfRefType::RefKind_Mut)
  11741. refType = CreateRefType(typedValue.mType);
  11742. if (!typedValue.mType->IsValuelessNonOpaqueType())
  11743. typedValue = MakeAddressable(typedValue, false, true);
  11744. return BfTypedValue(typedValue.mValue, refType);
  11745. }
  11746. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  11747. {
  11748. if (!typedValue.IsAddr())
  11749. return typedValue;
  11750. PopulateType(typedValue.mType);
  11751. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  11752. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  11753. if (typedValue.mValue.IsConst())
  11754. {
  11755. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  11756. if (constantValue != NULL)
  11757. {
  11758. if (constantValue->mConstType == BfConstType_GlobalVar)
  11759. {
  11760. auto globalVar = (BfGlobalVar*)constantValue;
  11761. if (globalVar->mName[0] == '#')
  11762. {
  11763. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  11764. if (result)
  11765. {
  11766. // We want to avoid 'unreachable code' issues from values that
  11767. // are technically constant but change depending on compilation context
  11768. if (mCurMethodState != NULL)
  11769. {
  11770. auto checkScope = mCurMethodState->mCurScope;
  11771. while (checkScope != NULL)
  11772. {
  11773. checkScope->mSupressNextUnreachable = true;
  11774. checkScope = checkScope->mPrevScope;
  11775. }
  11776. }
  11777. return result;
  11778. }
  11779. if (!mIsComptimeModule)
  11780. return GetDefaultTypedValue(typedValue.mType);
  11781. }
  11782. }
  11783. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  11784. {
  11785. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  11786. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  11787. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  11788. auto ceTypedValue = ceDebugger->GetAddr(constantValue);
  11789. if (ceTypedValue)
  11790. {
  11791. if ((typedValue.mType->IsObjectOrInterface()) || (typedValue.mType->IsPointer()) || (typedValue.mType->IsRef()))
  11792. {
  11793. void* data = ceContext->GetMemoryPtr((addr_ce)ceTypedValue.mAddr, sizeof(addr_ce));
  11794. if (data == NULL)
  11795. {
  11796. Fail("Invalid address", refNode);
  11797. return GetDefaultTypedValue(typedValue.mType);
  11798. }
  11799. uint64 dataAddr;
  11800. if (mSystem->mPtrSize == 4)
  11801. dataAddr = *(uint32*)data;
  11802. else
  11803. dataAddr = *(uint64*)data;
  11804. return BfTypedValue(mBfIRBuilder->CreateIntToPtr(
  11805. mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataAddr), mBfIRBuilder->MapType(typedValue.mType)), typedValue.mType);
  11806. }
  11807. auto constVal = ceContext->CreateConstant(this, ceContext->mMemory.mVals + ceTypedValue.mAddr, typedValue.mType);
  11808. if (!constVal)
  11809. {
  11810. Fail("Failed to create const", refNode);
  11811. return GetDefaultTypedValue(typedValue.mType);
  11812. }
  11813. return BfTypedValue(constVal, typedValue.mType);
  11814. }
  11815. }
  11816. }
  11817. }
  11818. BfIRValue loadedVal = typedValue.mValue;
  11819. if (loadedVal)
  11820. {
  11821. if (typedValue.mType->IsVar())
  11822. {
  11823. return BfTypedValue(loadedVal, typedValue.mType, false);
  11824. }
  11825. PopulateType(typedValue.mType, BfPopulateType_Data);
  11826. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile || typedValue.IsVolatile());
  11827. }
  11828. return BfTypedValue(loadedVal, typedValue.mType, false);
  11829. }
  11830. BfTypedValue BfModule::PrepareConst(BfTypedValue& typedValue)
  11831. {
  11832. if (!typedValue.mValue.IsConst())
  11833. return typedValue;
  11834. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  11835. if (constant->mTypeCode == BfTypeCode_StringId)
  11836. return GetTypedValueFromConstant(constant, mBfIRBuilder, typedValue.mType);
  11837. return typedValue;
  11838. }
  11839. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  11840. {
  11841. if (typedValue.IsSplat())
  11842. return AggregateSplat(typedValue);
  11843. if (typedValue.IsAddr())
  11844. return LoadValue(typedValue);
  11845. if ((typedValue.mType != NULL) && (typedValue.mType->IsParamsType()) && (!typedValue.IsParams()))
  11846. {
  11847. return GetDefaultTypedValue(ResolveTypeDef(mCompiler->mTupleTypeDef));
  11848. }
  11849. else if ((typedValue.IsParams()) && (typedValue.mType->IsGenericParam()))
  11850. {
  11851. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType);
  11852. }
  11853. return typedValue;
  11854. }
  11855. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  11856. {
  11857. if (!typedValue.IsSplat())
  11858. return typedValue;
  11859. BF_ASSERT(!mIsComptimeModule);
  11860. if (typedValue.mType->IsValuelessType())
  11861. return typedValue;
  11862. int elementIdx = 0;
  11863. auto _ExtractValue = [&](BfType* checkType)
  11864. {
  11865. if (valueArrPtr != NULL)
  11866. return valueArrPtr[elementIdx++];
  11867. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  11868. };
  11869. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11870. {
  11871. if (checkType->IsStruct())
  11872. {
  11873. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11874. auto checkTypeInstance = checkType->ToTypeInstance();
  11875. if (checkTypeInstance->mBaseType != NULL)
  11876. {
  11877. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  11878. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  11879. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  11880. }
  11881. if (checkTypeInstance->mIsUnion)
  11882. {
  11883. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11884. if (!unionInnerType->IsValuelessType())
  11885. {
  11886. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  11887. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  11888. }
  11889. if (checkTypeInstance->IsEnum())
  11890. {
  11891. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11892. BfIRValue fieldValue = checkTypeLambda(dscrType);
  11893. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  11894. }
  11895. }
  11896. else
  11897. {
  11898. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11899. {
  11900. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11901. if (fieldInstance->mDataIdx >= 0)
  11902. {
  11903. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  11904. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  11905. }
  11906. }
  11907. }
  11908. return curValue;
  11909. }
  11910. else if (checkType->IsMethodRef())
  11911. {
  11912. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11913. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11914. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11915. {
  11916. BfIRValue fieldValue;
  11917. auto checkType = methodRefType->GetCaptureType(dataIdx);
  11918. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11919. {
  11920. fieldValue = checkTypeLambda(checkType);
  11921. }
  11922. else
  11923. {
  11924. fieldValue = _ExtractValue(checkType);
  11925. }
  11926. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  11927. }
  11928. return curValue;
  11929. }
  11930. else if (!checkType->IsValuelessType())
  11931. {
  11932. return _ExtractValue(checkType);
  11933. }
  11934. return BfIRValue();
  11935. };
  11936. BfIRValue value = checkTypeLambda(typedValue.mType);
  11937. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  11938. }
  11939. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  11940. {
  11941. if (!typedValue.IsSplat())
  11942. return;
  11943. if (typedValue.mType->IsValuelessType())
  11944. return;
  11945. BF_ASSERT(!mIsComptimeModule);
  11946. /*static int sCallIdx = 0;
  11947. if (!mCompiler->mIsResolveOnly)
  11948. sCallIdx++;
  11949. int callIdx = sCallIdx;*/
  11950. int elementIdx = 0;
  11951. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  11952. {
  11953. if (checkType->IsStruct())
  11954. {
  11955. auto checkTypeInstance = checkType->ToTypeInstance();
  11956. if (checkTypeInstance->mBaseType != NULL)
  11957. {
  11958. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  11959. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  11960. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  11961. }
  11962. if (checkTypeInstance->mIsUnion)
  11963. {
  11964. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11965. if (!unionInnerType->IsValuelessType())
  11966. {
  11967. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  11968. checkTypeLambda(unionInnerType, fieldAddrVal);
  11969. }
  11970. if (checkTypeInstance->IsEnum())
  11971. {
  11972. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11973. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  11974. checkTypeLambda(dscrType, fieldAddrVal);
  11975. }
  11976. }
  11977. else
  11978. {
  11979. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11980. {
  11981. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11982. if (fieldInstance->mDataIdx >= 0)
  11983. {
  11984. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  11985. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  11986. }
  11987. }
  11988. }
  11989. }
  11990. else if (checkType->IsMethodRef())
  11991. {
  11992. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11993. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11994. {
  11995. auto dataType = methodRefType->GetCaptureType(dataIdx);
  11996. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  11997. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11998. {
  11999. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  12000. }
  12001. else
  12002. {
  12003. // static int sItrCount = 0;
  12004. // sItrCount++;
  12005. // int curItr = sItrCount;
  12006. // if (curItr == 1)
  12007. // {
  12008. // NOP;
  12009. // }
  12010. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  12011. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  12012. }
  12013. }
  12014. }
  12015. else if (!checkType->IsValuelessType())
  12016. {
  12017. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  12018. mBfIRBuilder->CreateStore(val, curAddrVal);
  12019. }
  12020. };
  12021. checkTypeLambda(typedValue.mType, addrVal);
  12022. }
  12023. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal, bool forceMutable, bool forceAddressable)
  12024. {
  12025. if (!typedVal)
  12026. return typedVal;
  12027. bool wasReadOnly = typedVal.IsReadOnly();
  12028. if ((forceAddressable) ||
  12029. ((typedVal.mType->IsValueType()) &&
  12030. (!typedVal.mType->IsValuelessNonOpaqueType())))
  12031. {
  12032. wasReadOnly = true; // Any non-addr is implicitly read-only
  12033. //static int gCallIdx = 0;
  12034. FixValueActualization(typedVal);
  12035. if (typedVal.IsAddr())
  12036. return typedVal;
  12037. BfType* type = typedVal.mType;
  12038. PopulateType(type);
  12039. BfIRValue tempVar;
  12040. if (typedVal.mValue.IsFake())
  12041. tempVar = mBfIRBuilder->GetFakeVal();
  12042. else
  12043. {
  12044. tempVar = CreateAlloca(type);
  12045. if (typedVal.IsSplat())
  12046. AggregateSplatIntoAddr(typedVal, tempVar);
  12047. else
  12048. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  12049. }
  12050. if (forceMutable)
  12051. wasReadOnly = false;
  12052. return BfTypedValue(tempVar, type,
  12053. typedVal.IsThis() ?
  12054. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  12055. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  12056. }
  12057. return LoadValue(typedVal);
  12058. }
  12059. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  12060. {
  12061. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  12062. typedValue.mKind = BfTypedValueKind_Addr;
  12063. return typedValue;
  12064. }
  12065. BfTypedValue BfModule::CopyValue(const BfTypedValue& typedValue)
  12066. {
  12067. return MakeAddressable(LoadValue(typedValue), true);
  12068. }
  12069. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  12070. {
  12071. BF_ASSERT(!mIsComptimeModule);
  12072. BfIRValue val;
  12073. if (typedValue.mValue.IsArg())
  12074. {
  12075. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  12076. if (isAddr != NULL)
  12077. {
  12078. if (wantType != NULL)
  12079. *isAddr = wantType->IsComposite();
  12080. else
  12081. *isAddr = false;
  12082. }
  12083. else if (wantType->IsComposite())
  12084. val = mBfIRBuilder->CreateLoad(val);
  12085. }
  12086. if (!val)
  12087. {
  12088. auto checkMethodState = mCurMethodState;
  12089. while (checkMethodState != NULL)
  12090. {
  12091. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  12092. {
  12093. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  12094. if (decompAddr == typedValue.mValue)
  12095. {
  12096. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  12097. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  12098. {
  12099. // This is really backing for a POINTER to a composite inside a methodRef
  12100. val = mBfIRBuilder->CreateLoad(val);
  12101. }
  12102. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  12103. {
  12104. *isAddr = true;
  12105. return val;
  12106. }
  12107. else
  12108. {
  12109. val = mBfIRBuilder->CreateAlignedLoad(val, wantType->mAlign);
  12110. break;
  12111. }
  12112. }
  12113. }
  12114. if (val)
  12115. break;
  12116. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  12117. {
  12118. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  12119. return mBfIRBuilder->GetFakeVal();
  12120. }
  12121. checkMethodState = checkMethodState->mPrevMethodState;
  12122. }
  12123. }
  12124. if (val)
  12125. {
  12126. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  12127. {
  12128. BF_ASSERT(wantType != NULL);
  12129. if (wantType != NULL)
  12130. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  12131. }
  12132. return val;
  12133. }
  12134. BFMODULE_FATAL(this, "Splat not found");
  12135. return BfIRValue();
  12136. }
  12137. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  12138. {
  12139. int useFieldIdx = fieldIdx;
  12140. BfType* fieldType = NULL;
  12141. if (fieldInstance != NULL)
  12142. {
  12143. fieldType = fieldInstance->mResolvedType;
  12144. if (typedValue.mType->IsUnion())
  12145. {
  12146. if (fieldIdx == 1)
  12147. {
  12148. if (typedValue.IsSplat())
  12149. {
  12150. bool isAddr = false;
  12151. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  12152. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  12153. }
  12154. }
  12155. }
  12156. }
  12157. else
  12158. {
  12159. if (typedValue.mType->IsPayloadEnum())
  12160. {
  12161. auto typeInst = typedValue.mType->ToTypeInstance();
  12162. if (fieldIdx == 1)
  12163. fieldType = typeInst->GetUnionInnerType();
  12164. else if (fieldIdx == 2)
  12165. {
  12166. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  12167. }
  12168. }
  12169. else if (typedValue.mType->IsUnion())
  12170. {
  12171. if (fieldIdx == 1)
  12172. {
  12173. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  12174. if (typedValue.IsSplat())
  12175. {
  12176. bool isAddr = false;
  12177. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  12178. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  12179. }
  12180. }
  12181. }
  12182. }
  12183. BF_ASSERT(typedValue.mType->IsStruct());
  12184. if (typedValue.IsSplat())
  12185. {
  12186. if (typedValue.mType->IsPayloadEnum())
  12187. {
  12188. if (fieldIdx == 1)
  12189. {
  12190. // Payload
  12191. auto typeInst = typedValue.mType->ToTypeInstance();
  12192. auto unionInnerType = typeInst->GetUnionInnerType();
  12193. bool isAddr = false;
  12194. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  12195. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  12196. }
  12197. if (fieldIdx == 2)
  12198. {
  12199. // Discriminator
  12200. auto typeInst = typedValue.mType->ToTypeInstance();
  12201. auto unionInnerType = typeInst->GetUnionInnerType();
  12202. auto dscrType = typeInst->GetDiscriminatorType();
  12203. int argIdx = typedValue.mValue.mId;
  12204. int componentIdx = 0;
  12205. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  12206. bool isAddr;
  12207. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  12208. return BfTypedValue(irVal, dscrType, isAddr);
  12209. }
  12210. }
  12211. int componentIdx = 0;
  12212. BfTypedValue retVal;
  12213. BfFieldInstance* wantFieldInstance = fieldInstance;
  12214. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  12215. {
  12216. if (checkType->IsStruct())
  12217. {
  12218. auto checkTypeInstance = checkType->ToTypeInstance();
  12219. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  12220. {
  12221. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  12222. fieldType = checkTypeInstance->GetUnionInnerType();
  12223. checkTypeLambda(fieldType);
  12224. if (checkType->IsEnum())
  12225. {
  12226. // Past discriminator...
  12227. componentIdx++;
  12228. }
  12229. return;
  12230. }
  12231. if (checkTypeInstance->mBaseType != NULL)
  12232. checkTypeLambda(checkTypeInstance->mBaseType);
  12233. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  12234. {
  12235. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  12236. if (fieldInstance == wantFieldInstance)
  12237. {
  12238. if (fieldInstance->mResolvedType->IsValuelessType())
  12239. {
  12240. retVal = GetDefaultTypedValue(fieldInstance->mResolvedType);
  12241. break;
  12242. }
  12243. bool isAddr = false;
  12244. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  12245. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  12246. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  12247. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  12248. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  12249. {
  12250. retVal = LoadValue(retVal);
  12251. }
  12252. break;
  12253. }
  12254. if (fieldInstance->mDataIdx >= 0)
  12255. checkTypeLambda(fieldInstance->GetResolvedType());
  12256. }
  12257. }
  12258. else if (!checkType->IsValuelessType())
  12259. {
  12260. componentIdx++;
  12261. //argIdx++;
  12262. }
  12263. };
  12264. checkTypeLambda(typedValue.mType);
  12265. BF_ASSERT(retVal);
  12266. return retVal;
  12267. }
  12268. if (typedValue.IsAddr())
  12269. {
  12270. BF_ASSERT(fieldType != NULL);
  12271. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  12272. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  12273. }
  12274. else
  12275. {
  12276. BF_ASSERT(fieldType != NULL);
  12277. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  12278. }
  12279. }
  12280. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  12281. {
  12282. if (typedValue.IsAddr())
  12283. {
  12284. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  12285. return mBfIRBuilder->CreateAlignedLoad(addrVal, typedValue.mType->mAlign);
  12286. }
  12287. if (typedValue.IsSplat())
  12288. typedValue = LoadOrAggregateValue(typedValue);
  12289. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  12290. }
  12291. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  12292. {
  12293. if (isElementIndex)
  12294. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  12295. else
  12296. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  12297. // if (elementType->IsSizeAligned())
  12298. // {
  12299. // if (isElementIndex)
  12300. // return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  12301. // else
  12302. // return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  12303. // }
  12304. //
  12305. // auto ptrType = CreatePointerType(elementType);
  12306. // auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  12307. // auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  12308. // auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  12309. // BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  12310. // BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  12311. // return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  12312. }
  12313. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  12314. {
  12315. if (elementType->IsSizeAligned())
  12316. {
  12317. if (isElementIndex)
  12318. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  12319. else
  12320. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  12321. }
  12322. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  12323. }
  12324. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  12325. {
  12326. if (modifyType == NULL)
  12327. modifyType = "modify";
  12328. if (typedValue.mType->IsVar())
  12329. return true;
  12330. if (typedValue.IsReadOnly())
  12331. {
  12332. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  12333. return false;
  12334. }
  12335. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  12336. {
  12337. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  12338. return false;
  12339. }
  12340. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  12341. {
  12342. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  12343. return false;
  12344. }
  12345. return true;
  12346. }
  12347. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  12348. {
  12349. // If one is an interface and the other is an impl, B is the impl
  12350. auto implOwner = methodB->GetOwner();
  12351. if (methodA->mMethodDef->mIsLocalMethod)
  12352. {
  12353. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  12354. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  12355. if (sepPosA != sepPosB)
  12356. return false;
  12357. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  12358. return false;
  12359. }
  12360. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  12361. return false;
  12362. if (methodA->mMethodDef->mAppendKind != methodB->mMethodDef->mAppendKind)
  12363. return false;
  12364. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  12365. return false;
  12366. if (methodA->mMethodDef->mHasComptime != methodB->mMethodDef->mHasComptime)
  12367. return false;
  12368. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  12369. return false;
  12370. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  12371. {
  12372. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  12373. return false;
  12374. }
  12375. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  12376. {
  12377. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  12378. return false;
  12379. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  12380. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  12381. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  12382. return false;
  12383. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  12384. return false;
  12385. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  12386. return false;
  12387. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  12388. {
  12389. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  12390. return false;
  12391. }
  12392. }
  12393. int implicitParamCountA = methodA->GetImplicitParamCount();
  12394. int implicitParamCountB = methodB->GetImplicitParamCount();
  12395. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  12396. return false;
  12397. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  12398. return false;
  12399. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  12400. {
  12401. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  12402. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  12403. return false;
  12404. }
  12405. // Compare generic params. Generic params are part of the method signature here
  12406. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  12407. return false;
  12408. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  12409. {
  12410. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  12411. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  12412. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  12413. return false;
  12414. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  12415. return false;
  12416. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  12417. return false;
  12418. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  12419. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  12420. return false;
  12421. }
  12422. return true;
  12423. }
  12424. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  12425. {
  12426. if (!CompareMethodSignatures(methodA, methodB))
  12427. return false;
  12428. if (methodA->mReturnType != methodB->mReturnType)
  12429. return false;
  12430. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  12431. return false;
  12432. return true;
  12433. }
  12434. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  12435. {
  12436. if ((iMethodInst->GetNumGenericParams() != 0) || (methodInstance->GetNumGenericParams() != 0))
  12437. return false;
  12438. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  12439. return false;
  12440. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  12441. return false;
  12442. if (iMethodInst->mMethodDef->mIsOperator)
  12443. {
  12444. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  12445. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  12446. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  12447. return false;
  12448. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  12449. return false;
  12450. }
  12451. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  12452. return false;
  12453. auto selfType = methodInstance->GetOwner();
  12454. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  12455. {
  12456. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  12457. return false;
  12458. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  12459. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  12460. iParamType = ResolveSelfType(iParamType, selfType);
  12461. methodParamType = ResolveSelfType(methodParamType, selfType);
  12462. if (!iParamType->IsGenericParam())
  12463. {
  12464. if (methodParamType != iParamType)
  12465. return false;
  12466. }
  12467. else
  12468. {
  12469. if (!methodParamType->IsGenericParam())
  12470. return false;
  12471. auto genericParamType = (BfGenericParamType*)methodParamType;
  12472. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  12473. return false;
  12474. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12475. bool hadInterface = false;
  12476. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  12477. if (interfaceConstraint == iParamType)
  12478. hadInterface = true;
  12479. if (!hadInterface)
  12480. return false;
  12481. }
  12482. }
  12483. return true;
  12484. }
  12485. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  12486. {
  12487. BfMethodInstance* methodInstance = methodRef;
  12488. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  12489. {
  12490. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  12491. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  12492. {
  12493. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  12494. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  12495. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12496. BfMethodRef methodRef = methodInstance;
  12497. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  12498. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  12499. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  12500. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  12501. (mIsReified))
  12502. {
  12503. specializedMethodRefInfo->mHasReifiedRef = true;
  12504. }
  12505. }
  12506. }
  12507. }
  12508. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  12509. {
  12510. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  12511. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12512. if (mBfIRBuilder == NULL)
  12513. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12514. if (methodInstance->GetOwner()->IsFunction())
  12515. {
  12516. // No actual ref needed- not an actual generated function
  12517. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12518. }
  12519. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  12520. if (!isGenFunction)
  12521. AddMethodReference(methodInstance, flags);
  12522. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  12523. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  12524. if (IsSkippingExtraResolveChecks())
  12525. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12526. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  12527. {
  12528. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12529. }
  12530. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12531. if ((methodInstance->mIsIntrinsic) || (methodInstance->mMethodDef->mIsExtern))
  12532. isInlined = false;
  12533. BfMethodRef methodRef = methodInstance;
  12534. if (isInlined)
  12535. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  12536. else
  12537. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  12538. if (!isGenFunction)
  12539. {
  12540. BfIRValue* irFuncPtr = NULL;
  12541. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  12542. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  12543. }
  12544. if (mAwaitingInitFinish)
  12545. FinishInit();
  12546. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  12547. if (!isGenFunction)
  12548. {
  12549. BF_ASSERT(func || methodInstance->mMethodInstanceGroup->mOwner->IsInterface());
  12550. mFuncReferences[methodRef] = func;
  12551. }
  12552. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  12553. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12554. {
  12555. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  12556. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  12557. // type instance
  12558. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  12559. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  12560. for (auto ownedTypeInst : mOwnedTypeInstances)
  12561. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  12562. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  12563. {
  12564. mIncompleteMethodCount++;
  12565. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12566. inlineMethodRequest->mType = methodInstance->GetOwner();
  12567. inlineMethodRequest->mFromModule = this;
  12568. inlineMethodRequest->mFunc = func;
  12569. inlineMethodRequest->mFromModuleRevision = mRevision;
  12570. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  12571. inlineMethodRequest->mMethodInstance = methodInstance;
  12572. BF_ASSERT(mIsModuleMutable);
  12573. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12574. }
  12575. }
  12576. return BfModuleMethodInstance(methodInstance, func);
  12577. }
  12578. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  12579. {
  12580. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  12581. if (mBfIRBuilder == NULL)
  12582. {
  12583. // To allow for custom attribute data
  12584. PrepareForIRWriting(typeInst);
  12585. }
  12586. BfModule* declareModule = this;
  12587. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  12588. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  12589. declareModule = declareModule->mParentModule;
  12590. // Check for attributes
  12591. if (typeInst == mContext->mBfObjectType)
  12592. {
  12593. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  12594. if (methodDecl != NULL)
  12595. {
  12596. auto attributesDirective = methodDecl->mAttributes;
  12597. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  12598. {
  12599. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  12600. sourceClassifier->VisitChild(attributesDirective);
  12601. }
  12602. }
  12603. }
  12604. else
  12605. {
  12606. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  12607. GetMethodCustomAttributes(methodInstance);
  12608. }
  12609. BF_ASSERT(mModuleOptions == NULL);
  12610. if (methodInstance->GetCustomAttributes() != NULL)
  12611. {
  12612. auto project = typeInst->mTypeDef->mProject;
  12613. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  12614. BfModuleOptions wantOptions = moduleOptions;
  12615. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  12616. if (typeOptions != NULL)
  12617. {
  12618. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  12619. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  12620. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  12621. }
  12622. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  12623. {
  12624. StringT<128> attrName;
  12625. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  12626. {
  12627. attrName.Clear();
  12628. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  12629. Array<int>* arrPtr;
  12630. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  12631. {
  12632. for (auto optionsIdx : *arrPtr)
  12633. {
  12634. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  12635. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  12636. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  12637. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  12638. }
  12639. }
  12640. }
  12641. }
  12642. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  12643. {
  12644. auto lastCheckModule = this;
  12645. auto checkModule = this->mNextAltModule;
  12646. while (checkModule != NULL)
  12647. {
  12648. if (*checkModule->mModuleOptions == wantOptions)
  12649. {
  12650. declareModule = checkModule;
  12651. break;
  12652. }
  12653. lastCheckModule = checkModule;
  12654. checkModule = checkModule->mNextAltModule;
  12655. }
  12656. // Not found?
  12657. if (declareModule == this)
  12658. {
  12659. String specModuleName = mModuleName + "@@";
  12660. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  12661. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  12662. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  12663. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  12664. declareModule = new BfModule(mContext, specModuleName);
  12665. declareModule->mProject = project;
  12666. declareModule->mModuleOptions = new BfModuleOptions();
  12667. *declareModule->mModuleOptions = wantOptions;
  12668. declareModule->mParentModule = lastCheckModule;
  12669. declareModule->Init();
  12670. lastCheckModule->mNextAltModule = declareModule;
  12671. }
  12672. }
  12673. }
  12674. declareModule->PrepareForIRWriting(typeInst);
  12675. return declareModule;
  12676. }
  12677. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType, BfModule* referencingModule)
  12678. {
  12679. if (methodDef->mMethodType == BfMethodType_Init)
  12680. return BfModuleMethodInstance();
  12681. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  12682. {
  12683. // Don't bother inlining for resolve-only
  12684. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12685. }
  12686. if (methodDef->mIsExtern)
  12687. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12688. bool processNow = false;
  12689. bool keepInCurrentModule = false;
  12690. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  12691. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  12692. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  12693. {
  12694. return BfModuleMethodInstance();
  12695. }
  12696. if (methodDef->mIsLocalMethod)
  12697. {
  12698. auto rootMethodState = mCurMethodState->GetRootMethodState();
  12699. BfLocalMethod* localMethod;
  12700. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  12701. {
  12702. // Handle the def in the correct method state
  12703. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  12704. }
  12705. BFMODULE_FATAL(this, "Cannot find local method");
  12706. return BfModuleMethodInstance();
  12707. }
  12708. #ifdef _DEBUG
  12709. for (auto arg : methodGenericArguments)
  12710. BF_ASSERT(!arg->IsVar());
  12711. #endif
  12712. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  12713. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  12714. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  12715. // a FinishInit
  12716. if ((typeInst->IsIncomplete()) &&
  12717. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  12718. {
  12719. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  12720. // for resolve-only because we don't differentiate between reified/unreified there
  12721. if ((methodDef->mIsStatic) /*&& (mIsComptimeModule)*/)
  12722. {
  12723. if (!typeInst->DefineStateAllowsStaticMethods())
  12724. PopulateType(typeInst, BfPopulateType_AllowStaticMethods);
  12725. }
  12726. else
  12727. PopulateType(typeInst, BfPopulateType_Full);
  12728. if (typeInst->mDefineState < BfTypeDefineState_Defined)
  12729. {
  12730. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12731. {
  12732. BfLogSysM("GetMethodInstance (DefineState < BfTypeDefineState_Defined)) bailing due to IsCePaused\n");
  12733. return BfModuleMethodInstance();
  12734. }
  12735. }
  12736. }
  12737. bool tryModuleMethodLookup = false;
  12738. BfModuleMethodInstance moduleMethodInst;
  12739. BfModule* instModule = typeInst->mModule;
  12740. if (keepInCurrentModule)
  12741. {
  12742. // Stay here
  12743. instModule = this;
  12744. }
  12745. if (this == mContext->mUnreifiedModule)
  12746. {
  12747. // Stay in this 'resolve only' module here
  12748. }
  12749. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  12750. {
  12751. BF_ASSERT(this == mContext->mUnreifiedModule);
  12752. }
  12753. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  12754. {
  12755. BF_ASSERT(instModule == mParentModule);
  12756. }
  12757. else if (instModule != this)
  12758. {
  12759. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12760. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  12761. if ((!mIsComptimeModule) && (!mIsReified) && (instModule->mIsReified))
  12762. {
  12763. BF_ASSERT(!mCompiler->mIsResolveOnly);
  12764. // A resolve-only module is specializing a method from a type in a reified module,
  12765. // we need to take care that this doesn't cause anything new to become reified
  12766. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  12767. if (!moduleMethodInstance)
  12768. return moduleMethodInstance;
  12769. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  12770. return moduleMethodInstance;
  12771. }
  12772. else
  12773. {
  12774. if ((!mIsComptimeModule) && (mIsReified) && (!instModule->mIsReified))
  12775. {
  12776. if (!typeInst->IsUnspecializedType())
  12777. {
  12778. if (!instModule->mReifyQueued)
  12779. {
  12780. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  12781. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  12782. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  12783. mContext->mReifyModuleWorkList.Add(instModule);
  12784. instModule->mReifyQueued = true;
  12785. }
  12786. BfLogSysM("REIFIED(GetMethodInstance QueueSpecializationRequest): %s %s MethodDef:%p RefModule:%s RefMethod:%p\n", TypeToString(typeInst).c_str(), methodDef->mName.c_str(), methodDef, mModuleName.c_str(), mCurMethodInstance);
  12787. // Sanity check
  12788. {
  12789. int methodIdx = methodDef->mIdx;
  12790. BfMethodDef* checkMethod = NULL;
  12791. if (foreignType != NULL)
  12792. checkMethod = foreignType->mTypeDef->mMethods[methodIdx];
  12793. else
  12794. checkMethod = typeInst->mTypeDef->mMethods[methodIdx];
  12795. if (checkMethod != methodDef)
  12796. {
  12797. BfLogSysM(" MISMATCH. Got:%p Expected:%p\n", checkMethod, methodDef);
  12798. BF_ASSERT(checkMethod->mName == methodDef->mName);
  12799. methodDef = checkMethod;
  12800. }
  12801. }
  12802. // This ensures that the method will actually be created when it gets reified
  12803. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  12804. specializationRequest->mFromModule = typeInst->mModule;
  12805. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  12806. specializationRequest->Init(typeInst, foreignType, methodDef);
  12807. //specializationRequest->mMethodDef = methodDef;
  12808. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  12809. specializationRequest->mType = typeInst;
  12810. specializationRequest->mFlags = flags;
  12811. }
  12812. }
  12813. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12814. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoReference);
  12815. if (mIsComptimeModule)
  12816. {
  12817. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12818. if (!mCompiler->mIsResolveOnly)
  12819. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification | BfGetMethodInstanceFlag_Unreified | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12820. }
  12821. // Not extern
  12822. // Create the instance in the proper module and then create a reference in this one
  12823. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType, this);
  12824. if (!moduleMethodInst)
  12825. return moduleMethodInst;
  12826. tryModuleMethodLookup = true;
  12827. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  12828. {
  12829. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  12830. }
  12831. }
  12832. }
  12833. if (tryModuleMethodLookup)
  12834. {
  12835. SetMethodDependency(moduleMethodInst.mMethodInstance);
  12836. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  12837. }
  12838. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  12839. {
  12840. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  12841. if (moduleMethodInstance)
  12842. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  12843. return moduleMethodInst;
  12844. }
  12845. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  12846. bool hadConcreteInterfaceGenericArgument = false;
  12847. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  12848. isReified = false;
  12849. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  12850. {
  12851. isReified = false;
  12852. }
  12853. BfTypeVector sanitizedMethodGenericArguments;
  12854. SizedArray<BfProject*, 4> projectList;
  12855. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  12856. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  12857. isUnspecializedPass = false;
  12858. // 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
  12859. bool isExternalExtensionMethod = false;
  12860. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  12861. {
  12862. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) &&
  12863. (methodDef->mDeclaringType != NULL) &&
  12864. (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  12865. {
  12866. auto specProject = methodDef->mDeclaringType->mProject;
  12867. isExternalExtensionMethod = true;
  12868. if (typeInst->IsGenericTypeInstance())
  12869. {
  12870. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12871. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12872. genericTypeInst->GenerateProjectsReferenced();
  12873. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  12874. {
  12875. // This is a generic type where a generic param is already confined to the project in question
  12876. isExternalExtensionMethod = false;
  12877. }
  12878. }
  12879. if (isExternalExtensionMethod)
  12880. {
  12881. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  12882. projectList.push_back(methodDef->mDeclaringType->mProject);
  12883. }
  12884. }
  12885. }
  12886. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  12887. {
  12888. int typeProjectsCounts = 0;
  12889. if (typeInst->IsGenericTypeInstance())
  12890. {
  12891. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12892. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12893. genericTypeInst->GenerateProjectsReferenced();
  12894. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  12895. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  12896. }
  12897. else
  12898. {
  12899. typeProjectsCounts = 1;
  12900. projectList.Insert(0, typeInst->mTypeDef->mProject);
  12901. }
  12902. isUnspecializedPass = true;
  12903. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  12904. {
  12905. auto genericArgType = methodGenericArguments[genericArgIdx];
  12906. //BF_ASSERT(!genericArgType->IsRef());
  12907. if (genericArgType->IsConcreteInterfaceType())
  12908. {
  12909. hadConcreteInterfaceGenericArgument = true;
  12910. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  12911. genericArgType = concreteInterfaceType->mInterface;
  12912. }
  12913. if (genericArgType->IsGenericParam())
  12914. {
  12915. auto genericParam = (BfGenericParamType*) genericArgType;
  12916. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  12917. isUnspecializedPass = false;
  12918. }
  12919. else
  12920. {
  12921. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  12922. isUnspecializedPass = false;
  12923. }
  12924. sanitizedMethodGenericArguments.push_back(genericArgType);
  12925. }
  12926. if ((int)projectList.size() > typeProjectsCounts)
  12927. {
  12928. // Just leave the new items
  12929. projectList.RemoveRange(0, typeProjectsCounts);
  12930. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  12931. {
  12932. return lhs->mName < rhs->mName;
  12933. });
  12934. }
  12935. else
  12936. {
  12937. projectList.Clear();
  12938. }
  12939. }
  12940. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  12941. BfMethodInstanceGroup* methodInstGroup = NULL;
  12942. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12943. {
  12944. BF_ASSERT(!typeInst->IsInterface());
  12945. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  12946. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  12947. {
  12948. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  12949. // if (checkGroup.mDefault == NULL)
  12950. // {
  12951. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  12952. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  12953. // methodInstGroup = &checkGroup;
  12954. // break;
  12955. // }
  12956. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  12957. {
  12958. methodInstGroup = &checkGroup;
  12959. break;
  12960. }
  12961. }
  12962. if (methodInstGroup == NULL)
  12963. {
  12964. if (lookupMethodGenericArguments.size() != 0)
  12965. {
  12966. BF_ASSERT((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0);
  12967. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12968. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12969. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12970. }
  12971. else
  12972. {
  12973. // Allocate a new entry
  12974. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  12975. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  12976. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  12977. methodInstGroup->mOwner = typeInst;
  12978. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12979. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12980. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  12981. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12982. else
  12983. {
  12984. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  12985. if (!mIsScratchModule)
  12986. mOnDemandMethodCount++;
  12987. }
  12988. }
  12989. }
  12990. }
  12991. else
  12992. {
  12993. if (methodDef->mIdx >= typeInst->mMethodInstanceGroups.mSize)
  12994. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  12995. if (methodDef->mIdx >= typeInst->mMethodInstanceGroups.mSize)
  12996. {
  12997. InternalError("GetMethodInstance OOB error", methodDef->GetRefNode());
  12998. return BfModuleMethodInstance();
  12999. }
  13000. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  13001. }
  13002. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  13003. {
  13004. if (typeInst->mDefineState > BfTypeDefineState_DefinedAndMethodsSlotted)
  13005. {
  13006. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  13007. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  13008. }
  13009. }
  13010. BfIRFunction prevIRFunc;
  13011. bool doingRedeclare = false;
  13012. BfMethodInstance* methodInstance = NULL;
  13013. auto _SetReified = [&]()
  13014. {
  13015. if (!mCompiler->mIsResolveOnly)
  13016. BF_ASSERT(mCompiler->mCompileState <= BfCompiler::CompileState_Normal);
  13017. methodInstance->mIsReified = true;
  13018. };
  13019. if (lookupMethodGenericArguments.size() == 0)
  13020. {
  13021. methodInstance = methodInstGroup->mDefault;
  13022. if ((methodInstance != NULL) && ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0))
  13023. return methodInstance;
  13024. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  13025. {
  13026. MarkDerivedDirty(typeInst);
  13027. if (!HasCompiledOutput())
  13028. {
  13029. BfLogSysM("Marking non-compiled-output module method instance as reified: %p\n", methodInstance);
  13030. _SetReified();
  13031. CheckHotMethod(methodInstance, "");
  13032. }
  13033. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  13034. {
  13035. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  13036. // the specializations to handle that for us
  13037. return BfModuleMethodInstance(methodInstance);
  13038. }
  13039. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  13040. {
  13041. if (methodDef->mIsAbstract)
  13042. {
  13043. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  13044. _SetReified();
  13045. }
  13046. else
  13047. {
  13048. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  13049. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  13050. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  13051. doingRedeclare = true;
  13052. mOnDemandMethodCount++;
  13053. VerifyOnDemandMethods();
  13054. }
  13055. }
  13056. else
  13057. {
  13058. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  13059. // We haven't processed it yet
  13060. _SetReified();
  13061. CheckHotMethod(methodInstance, "");
  13062. if (methodInstance->mDeclModule == this)
  13063. {
  13064. if (methodInstance->mMethodProcessRequest != NULL)
  13065. {
  13066. // Disconnect method process request
  13067. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  13068. }
  13069. }
  13070. else
  13071. {
  13072. if (methodInstance->mMethodProcessRequest != NULL)
  13073. {
  13074. // Disconnect method process request
  13075. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  13076. methodInstance->mMethodProcessRequest = NULL;
  13077. }
  13078. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  13079. {
  13080. // Add new request in proper module
  13081. methodInstance->mDeclModule = this;
  13082. }
  13083. else
  13084. {
  13085. if (methodInstance->mDeclModule == NULL)
  13086. {
  13087. //
  13088. }
  13089. else if (methodInstance->mDeclModule != this)
  13090. {
  13091. // Is from specialized module?
  13092. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  13093. }
  13094. }
  13095. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  13096. {
  13097. methodInstance->mIRFunction = BfIRFunction();
  13098. if (!mIsModuleMutable)
  13099. StartExtension();
  13100. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  13101. {
  13102. StringT<512> mangledName;
  13103. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  13104. bool isIntrinsic = false;
  13105. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  13106. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  13107. }
  13108. }
  13109. AddMethodToWorkList(methodInstance);
  13110. }
  13111. }
  13112. }
  13113. }
  13114. else
  13115. {
  13116. if (methodInstGroup->mDefault == NULL)
  13117. {
  13118. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  13119. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  13120. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  13121. }
  13122. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  13123. if (methodInstGroup->mMethodSpecializationMap == NULL)
  13124. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  13125. BfMethodInstance** methodInstancePtr = NULL;
  13126. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  13127. {
  13128. methodInstance = *methodInstancePtr;
  13129. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  13130. return methodInstance;
  13131. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  13132. {
  13133. BfLogSysM("Setting mRequestedByAutocomplete=false for method instance %p\n", methodInstance);
  13134. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  13135. if (methodInstance->mMethodProcessRequest == NULL)
  13136. AddMethodToWorkList(methodInstance);
  13137. methodInstance->mRequestedByAutocomplete = false;
  13138. }
  13139. if ((isReified) && (!methodInstance->mIsReified))
  13140. {
  13141. MarkDerivedDirty(typeInst);
  13142. if (methodInstance->mHasBeenProcessed)
  13143. {
  13144. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  13145. delete methodInstance;
  13146. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  13147. methodInstance = NULL;
  13148. }
  13149. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  13150. {
  13151. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  13152. delete methodInstance;
  13153. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  13154. methodInstance = NULL;
  13155. }
  13156. else
  13157. {
  13158. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  13159. // We haven't processed it yet
  13160. _SetReified();
  13161. CheckHotMethod(methodInstance, "");
  13162. if (methodInstance->mMethodProcessRequest == NULL)
  13163. AddMethodToWorkList(methodInstance);
  13164. }
  13165. }
  13166. }
  13167. }
  13168. auto _CheckDllImport = [&]()
  13169. {
  13170. auto declModule = methodInstance->mDeclModule;
  13171. if ((!methodInstance->mIRFunction) && (declModule->mIsModuleMutable) && (!declModule->mBfIRBuilder->mIgnoreWrites))
  13172. {
  13173. auto importKind = methodInstance->GetImportCallKind();
  13174. if (importKind != BfImportCallKind_None)
  13175. {
  13176. BfLogSysM("DllImportGlobalVar creating %p in module %p from module %p\n", methodInstance, declModule, this);
  13177. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13178. auto func = declModule->CreateDllImportGlobalVar(methodInstance, true);
  13179. BF_ASSERT(func);
  13180. declModule->mFuncReferences[methodInstance] = func;
  13181. }
  13182. }
  13183. };
  13184. if ((methodInstance != NULL) && (!doingRedeclare))
  13185. {
  13186. SetMethodDependency(methodInstance);
  13187. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  13188. {
  13189. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  13190. BF_ASSERT(!methodInstance->mIsReified);*/
  13191. if ((!mCompiler->mIsResolveOnly) && (isReified))
  13192. {
  13193. auto refModule = referencingModule;
  13194. if (refModule == NULL)
  13195. refModule = this;
  13196. BfLogSysM("REIFIED(GetMethodInstance Reference): %s MethodDef:%p MethodInst:%p RefModule:%s RefMethod:%p\n", methodInstance->mMethodDef->mName.c_str(), methodDef, methodInstance, refModule->mModuleName.c_str(), refModule->mCurMethodInstance);
  13197. }
  13198. if (methodInstance->mIsReified != isReified)
  13199. {
  13200. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  13201. }
  13202. if ((!isReified) &&
  13203. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  13204. {
  13205. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  13206. methodInstance->mIRFunction = BfIRFunction();
  13207. }
  13208. methodInstance->mIsReified = isReified;
  13209. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  13210. {
  13211. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  13212. }
  13213. if (!methodInstance->mMethodDef->mIsAbstract)
  13214. {
  13215. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  13216. {
  13217. // Wait until unreified
  13218. }
  13219. else
  13220. AddMethodToWorkList(methodInstance);
  13221. }
  13222. else
  13223. {
  13224. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13225. auto owningModule = methodInstance->GetOwner()->mModule;
  13226. if (!owningModule->mIsScratchModule)
  13227. {
  13228. owningModule->mOnDemandMethodCount--;
  13229. owningModule->VerifyOnDemandMethods();
  13230. }
  13231. }
  13232. }
  13233. if (mExtensionCount > 0)
  13234. {
  13235. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  13236. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  13237. {
  13238. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  13239. if (mAwaitingInitFinish)
  13240. FinishInit();
  13241. // We need to refer to a function that was defined in a prior module
  13242. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  13243. if (methodInstance->mIsIntrinsic)
  13244. isInlined = false;
  13245. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  13246. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  13247. methodInstance->mDeclModule = this;
  13248. // Add this inlined def to ourselves
  13249. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  13250. {
  13251. mIncompleteMethodCount++;
  13252. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  13253. inlineMethodRequest->mType = typeInst;
  13254. inlineMethodRequest->mFromModule = this;
  13255. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  13256. inlineMethodRequest->mFromModuleRevision = mRevision;
  13257. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  13258. inlineMethodRequest->mMethodInstance = methodInstance;
  13259. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  13260. BF_ASSERT(mIsModuleMutable);
  13261. }
  13262. }
  13263. }
  13264. if (IsSkippingExtraResolveChecks())
  13265. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  13266. else
  13267. {
  13268. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  13269. return methodInstance;
  13270. if (methodInstance->mDeclModule != this)
  13271. return ReferenceExternalMethodInstance(methodInstance, flags);
  13272. _CheckDllImport();
  13273. return BfModuleMethodInstance(methodInstance);
  13274. }
  13275. }
  13276. if (!doingRedeclare)
  13277. {
  13278. BfModule* specModule = NULL;
  13279. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  13280. {
  13281. specModule = GetSpecializedMethodModule(projectList);
  13282. }
  13283. if ((specModule != NULL) && (specModule != this))
  13284. {
  13285. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  13286. if (mAwaitingInitFinish)
  13287. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  13288. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  13289. return specMethodInstance.mMethodInstance;
  13290. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  13291. }
  13292. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  13293. {
  13294. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  13295. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  13296. }
  13297. }
  13298. if (methodInstance == NULL)
  13299. {
  13300. if (!mCompiler->EnsureCeUnpaused(typeInst))
  13301. {
  13302. BfLogSysM("GetMethodInstance (methodInstance == NULL) bailing due to IsCePaused\n");
  13303. return BfModuleMethodInstance();
  13304. }
  13305. if (lookupMethodGenericArguments.size() == 0)
  13306. {
  13307. BF_ASSERT(methodInstGroup->mDefault == NULL);
  13308. methodInstance = new BfMethodInstance();
  13309. methodInstGroup->mDefault = methodInstance;
  13310. BF_ASSERT(typeInst->mDefineState > BfTypeDefineState_Declared);
  13311. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  13312. }
  13313. else
  13314. {
  13315. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  13316. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  13317. depthExceeded = true;
  13318. if (depthExceeded)
  13319. {
  13320. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  13321. return BfModuleMethodInstance();
  13322. }
  13323. BfMethodInstance** methodInstancePtr = NULL;
  13324. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  13325. BF_ASSERT(added);
  13326. methodInstance = new BfMethodInstance();
  13327. *methodInstancePtr = methodInstance;
  13328. if (mCompiler->IsAutocomplete())
  13329. methodInstance->mRequestedByAutocomplete = true;
  13330. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  13331. }
  13332. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  13333. methodInstance->mIRFunction = prevIRFunc; // Take it over
  13334. }
  13335. methodInstance->mMethodDef = methodDef;
  13336. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  13337. methodInstance->mMethodInstanceGroup = methodInstGroup;
  13338. methodInstance->mIsReified = isReified;
  13339. SetupMethodIdHash(methodInstance);
  13340. if (hadConcreteInterfaceGenericArgument)
  13341. methodInstance->mIgnoreBody = true;
  13342. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  13343. {
  13344. methodInstance->mIsForeignMethodDef = true;
  13345. BF_ASSERT(foreignType != NULL);
  13346. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  13347. }
  13348. if ((typeInst->IsInstanceOf(mCompiler->mValueTypeTypeDef)) && (methodDef->mName == BF_METHODNAME_EQUALS))
  13349. {
  13350. if (!lookupMethodGenericArguments.empty())
  13351. {
  13352. auto compareType = lookupMethodGenericArguments[0];
  13353. PopulateType(compareType, BfPopulateType_Data);
  13354. if (compareType->IsSplattable())
  13355. methodInstance->mAlwaysInline = true;
  13356. }
  13357. }
  13358. if (methodDef->mMethodType == BfMethodType_Init)
  13359. {
  13360. methodInstance->mMangleWithIdx = true;
  13361. }
  13362. if (methodDef->mAppendKind > BfAllowAppendKind_No)
  13363. {
  13364. methodInstance->mMangleWithIdx = true;
  13365. }
  13366. BF_ASSERT(typeInst == methodInstance->GetOwner());
  13367. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13368. if (isUnspecializedPass)
  13369. {
  13370. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  13371. {
  13372. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  13373. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  13374. }
  13375. }
  13376. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  13377. {
  13378. if (!sanitizedMethodGenericArguments.IsEmpty())
  13379. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  13380. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  13381. {
  13382. Fail("Internal error");
  13383. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  13384. return NULL;
  13385. }
  13386. for (auto genericArg : sanitizedMethodGenericArguments)
  13387. {
  13388. if (genericArg->IsPrimitiveType())
  13389. genericArg = GetWrappedStructType(genericArg);
  13390. if (genericArg != NULL)
  13391. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  13392. }
  13393. }
  13394. // Generic constraints
  13395. if (!methodDef->mGenericParams.IsEmpty())
  13396. {
  13397. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  13398. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  13399. {
  13400. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  13401. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  13402. }
  13403. }
  13404. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  13405. {
  13406. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  13407. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  13408. }
  13409. bool addToWorkList = !processNow;
  13410. if (mCompiler->GetAutoComplete() != NULL)
  13411. {
  13412. if (typeInst->IsSpecializedByAutoCompleteMethod())
  13413. addToWorkList = false;
  13414. if (methodInstance->mRequestedByAutocomplete)
  13415. addToWorkList = false;
  13416. }
  13417. BfModule* declareModule;
  13418. //
  13419. {
  13420. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13421. declareModule = GetOrCreateMethodModule(methodInstance);
  13422. }
  13423. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  13424. declareModule = methodInstance->mDeclModule;
  13425. BF_ASSERT(declareModule != NULL);
  13426. methodInstance->mDeclModule = declareModule;
  13427. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  13428. {
  13429. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  13430. // of a reified module -
  13431. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  13432. // BUT if we don't reify it then we have to remove the body after processing.
  13433. // 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
  13434. // the proper reified module.
  13435. declareModule = mContext->mUnreifiedModule;
  13436. }
  13437. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  13438. {
  13439. if (!methodInstance->mIsReified)
  13440. {
  13441. declareModule = mContext->mUnreifiedModule;
  13442. }
  13443. else
  13444. {
  13445. declareModule->PrepareForIRWriting(methodInstance->GetOwner());
  13446. }
  13447. }
  13448. SetMethodDependency(methodInstance);
  13449. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  13450. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  13451. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  13452. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  13453. {
  13454. // For mixins we only process the unspecialized version
  13455. addToWorkList = false;
  13456. }
  13457. if (((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0) && (methodInstGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  13458. {
  13459. addToWorkList = false;
  13460. }
  13461. // if ((flags & BfGetMethodInstanceFlag_NoReference) != 0)
  13462. // addToWorkList = false;
  13463. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  13464. if (processNow)
  13465. {
  13466. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  13467. ProcessMethod(methodInstance);
  13468. }
  13469. if (IsSkippingExtraResolveChecks())
  13470. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  13471. if (methodInstance->mDeclModule != this)
  13472. return ReferenceExternalMethodInstance(methodInstance, flags);
  13473. if (doingRedeclare)
  13474. {
  13475. _CheckDllImport();
  13476. }
  13477. return BfModuleMethodInstance(methodInstance);
  13478. }
  13479. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  13480. {
  13481. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  13482. if (methodInstance->mIsForeignMethodDef)
  13483. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  13484. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  13485. }
  13486. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  13487. {
  13488. if (!methodInstance->mMethodDef->mIsLocalMethod)
  13489. return NULL;
  13490. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  13491. if (outerLocal == NULL)
  13492. return NULL;
  13493. BfTypeVector genericArgs;
  13494. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  13495. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  13496. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  13497. }
  13498. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  13499. {
  13500. HashContext hashCtx;
  13501. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  13502. {
  13503. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  13504. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  13505. if (methodInstance->GetNumGenericArguments() != 0)
  13506. {
  13507. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  13508. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13509. hashCtx.Mixin(methodGenericArg->mTypeId);
  13510. }
  13511. };
  13512. _MixinMethodInstance(methodInstance);
  13513. if (methodInstance->mMethodDef->mIsLocalMethod)
  13514. {
  13515. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  13516. if (outmostMethodInstance != NULL)
  13517. {
  13518. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  13519. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  13520. }
  13521. }
  13522. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  13523. }
  13524. bool BfModule::CheckUseMethodInstance(BfMethodInstance* methodInstance, BfAstNode* refNode)
  13525. {
  13526. if (methodInstance->mHasBeenDeclared)
  13527. return true;
  13528. Fail(StrFormat("Circular reference in method instance '%s'", MethodToString(methodInstance).c_str()), refNode);
  13529. return false;
  13530. }
  13531. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  13532. {
  13533. BfIRValue globalValue;
  13534. BfIRValue* globalValuePtr = NULL;
  13535. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  13536. {
  13537. globalValue = *globalValuePtr;
  13538. }
  13539. if (!globalValue)
  13540. {
  13541. // This is necessary to reify the interface type
  13542. PopulateType(ifaceType);
  13543. StringT<512> slotVarName;
  13544. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  13545. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  13546. BfIRValue value;
  13547. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  13548. {
  13549. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  13550. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  13551. int virtSlotIdx = ifaceType->mSlotNum + 1;
  13552. value = GetConstValue32(virtSlotIdx);*/
  13553. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  13554. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  13555. }
  13556. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  13557. mInterfaceSlotRefs[ifaceType] = globalValue;
  13558. // Make sure we reify
  13559. PopulateType(ifaceType, BfPopulateType_Declaration);
  13560. AddDependency(ifaceType, mCurTypeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  13561. }
  13562. return mBfIRBuilder->CreateAlignedLoad(globalValue/*, "slotOfs"*/, 4);
  13563. }
  13564. void BfModule::HadSlotCountDependency()
  13565. {
  13566. if (mCompiler->mIsResolveOnly)
  13567. return;
  13568. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  13569. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  13570. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  13571. }
  13572. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  13573. {
  13574. if (str == "#IsComptime")
  13575. {
  13576. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsComptimeModule ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13577. }
  13578. if (str == "#IsBuilding")
  13579. {
  13580. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (!mCompiler->mIsResolveOnly) ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13581. }
  13582. if (str == "#IsReified")
  13583. {
  13584. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsReified ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13585. }
  13586. if (str == "#CompileRev")
  13587. {
  13588. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mRevision), GetPrimitiveType(BfTypeCode_Int32));
  13589. }
  13590. if (str == "#NextId")
  13591. {
  13592. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)++mCompiler->mUniqueId), GetPrimitiveType(BfTypeCode_Int32));
  13593. }
  13594. if (str == "#ModuleName")
  13595. {
  13596. return BfTypedValue(GetStringObjectValue(mModuleName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13597. }
  13598. if (str == "#ProjectName")
  13599. {
  13600. if (mProject != NULL)
  13601. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13602. }
  13603. if (str == "#AllocStackCount")
  13604. {
  13605. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mOptions.mAllocStackCount), GetPrimitiveType(BfTypeCode_Int32));
  13606. }
  13607. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  13608. {
  13609. if (str == "#CallerLineNum")
  13610. {
  13611. return BfTypedValue(GetConstValue(mCurMethodState->mMixinState->mInjectFilePosition.mCurLine + 1), GetPrimitiveType(BfTypeCode_Int32));
  13612. }
  13613. else if (str == "#CallerFilePath")
  13614. {
  13615. String filePath = "";
  13616. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13617. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13618. return BfTypedValue(GetStringObjectValue(filePath), ResolveTypeDef(mCompiler->mStringTypeDef));
  13619. }
  13620. else if (str == "#CallerFileName")
  13621. {
  13622. String filePath = "";
  13623. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13624. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13625. return BfTypedValue(GetStringObjectValue(GetFileName(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13626. }
  13627. else if (str == "#CallerFileDir")
  13628. {
  13629. String filePath = "";
  13630. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13631. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13632. return BfTypedValue(GetStringObjectValue(GetFileDir(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13633. }
  13634. else if (str == "#CallerTypeName")
  13635. {
  13636. String typeName = "";
  13637. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13638. typeName = TypeToString(mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner());
  13639. return BfTypedValue(GetStringObjectValue(typeName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13640. }
  13641. else if (str == "#CallerType")
  13642. {
  13643. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  13644. BfType* type = NULL;
  13645. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13646. type = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  13647. if (type != NULL)
  13648. {
  13649. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  13650. return BfTypedValue(CreateTypeDataRef(type), typeType);
  13651. }
  13652. }
  13653. else if (str == "#CallerMemberName")
  13654. {
  13655. String memberName = "";
  13656. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13657. memberName = MethodToString(mCurMethodState->mMixinState->mMixinMethodInstance);
  13658. return BfTypedValue(GetStringObjectValue(memberName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13659. }
  13660. else if (str == "#CallerProject")
  13661. {
  13662. BfProject* project = NULL;
  13663. project = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mProject;
  13664. if (project != NULL)
  13665. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13666. }
  13667. }
  13668. if (str == "#TimeLocal")
  13669. {
  13670. time_t rawtime;
  13671. time(&rawtime);
  13672. tm* timeinfo = localtime(&rawtime);
  13673. char result[32];
  13674. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  13675. 1900 + timeinfo->tm_year,
  13676. timeinfo->tm_mon + 1,
  13677. timeinfo->tm_mday,
  13678. timeinfo->tm_hour,
  13679. timeinfo->tm_min,
  13680. timeinfo->tm_sec);
  13681. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  13682. }
  13683. return BfTypedValue();
  13684. }
  13685. BfTypedValue BfModule::GetCompilerFieldValue(BfTypedValue typedValue)
  13686. {
  13687. if (!typedValue.IsAddr())
  13688. return BfTypedValue();
  13689. if (typedValue.mValue.IsConst())
  13690. {
  13691. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  13692. if (constantValue != NULL)
  13693. {
  13694. if (constantValue->mConstType == BfConstType_GlobalVar)
  13695. {
  13696. auto globalVar = (BfGlobalVar*)constantValue;
  13697. if (globalVar->mName[0] == '#')
  13698. {
  13699. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  13700. return result;
  13701. }
  13702. }
  13703. }
  13704. }
  13705. return BfTypedValue();
  13706. }
  13707. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  13708. {
  13709. BfIRValue globalValue;
  13710. auto fieldDef = fieldInstance->GetFieldDef();
  13711. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  13712. {
  13713. if (fieldInstance->mConstIdx != -1)
  13714. {
  13715. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  13716. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  13717. }
  13718. else
  13719. {
  13720. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  13721. }
  13722. }
  13723. if ((mIsScratchModule) && (mCompiler->mIsResolveOnly) && (!fieldInstance->mOwner->IsInstanceOf(mCompiler->mCompilerTypeDef)))
  13724. {
  13725. // Just fake it for the extern and unspecialized modules
  13726. // We can't do this for compilation because unreified methods with default params need to get actual global variable refs
  13727. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr)), fieldInstance->GetResolvedType(), true);
  13728. }
  13729. BfIRValue* globalValuePtr = NULL;
  13730. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  13731. {
  13732. globalValue = *globalValuePtr;
  13733. BF_ASSERT(globalValue);
  13734. auto globalVar = (BfGlobalVar*)mBfIRBuilder->GetConstant(globalValue);
  13735. if ((globalVar->mStreamId == -1) && (!mBfIRBuilder->mIgnoreWrites))
  13736. {
  13737. mBfIRBuilder->MapType(fieldInstance->mResolvedType);
  13738. mBfIRBuilder->CreateGlobalVariable(globalValue);
  13739. }
  13740. }
  13741. else
  13742. {
  13743. StringT<512> staticVarName;
  13744. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  13745. auto typeType = fieldInstance->GetResolvedType();
  13746. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  13747. {
  13748. typeType = typeType->GetUnderlyingType();
  13749. }
  13750. if (mIsComptimeModule)
  13751. {
  13752. mCompiler->mCeMachine->QueueStaticField(fieldInstance, staticVarName);
  13753. }
  13754. PopulateType(typeType);
  13755. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  13756. {
  13757. BfIRType irType = mBfIRBuilder->MapType(typeType);
  13758. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  13759. globalValue = mBfIRBuilder->CreateGlobalVariable(
  13760. irType,
  13761. false,
  13762. BfIRLinkageType_External,
  13763. BfIRValue(),
  13764. staticVarName,
  13765. IsThreadLocal(fieldInstance));
  13766. BF_ASSERT(globalValue);
  13767. mStaticFieldRefs[fieldInstance] = globalValue;
  13768. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  13769. }
  13770. }
  13771. auto type = fieldInstance->GetResolvedType();
  13772. if (type->IsValuelessType())
  13773. return BfTypedValue(globalValue, type);
  13774. if (fieldDef->mIsVolatile)
  13775. return BfTypedValue(globalValue, type, BfTypedValueKind_VolatileAddr);
  13776. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  13777. }
  13778. BfFieldInstance* BfModule::GetFieldInstance(BfTypeInstance* typeInst, int fieldIdx, const char* fieldName)
  13779. {
  13780. if (typeInst->IsDataIncomplete())
  13781. PopulateType(typeInst);
  13782. if (fieldIdx >= typeInst->mFieldInstances.mSize)
  13783. {
  13784. Fail(StrFormat("Invalid field data in type '%s'", TypeToString(typeInst).c_str()));
  13785. return 0;
  13786. }
  13787. return &typeInst->mFieldInstances[fieldIdx];
  13788. }
  13789. void BfModule::MarkUsingThis()
  13790. {
  13791. auto useMethodState = mCurMethodState;
  13792. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13793. {
  13794. useMethodState = useMethodState->mPrevMethodState;
  13795. }
  13796. if ((useMethodState != NULL) && (!useMethodState->mLocals.IsEmpty()))
  13797. {
  13798. auto localVar = useMethodState->mLocals[0];
  13799. if (localVar->mIsThis)
  13800. localVar->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13801. }
  13802. }
  13803. BfTypedValue BfModule::GetThis(bool markUsing)
  13804. {
  13805. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  13806. {
  13807. if (mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis)
  13808. return mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis;
  13809. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  13810. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  13811. if ((activeFrame != NULL) && (activeFrame->mFunction->mDbgInfo != NULL))
  13812. {
  13813. for (auto& dbgVar : activeFrame->mFunction->mDbgInfo->mVariables)
  13814. {
  13815. if (dbgVar.mName == "this")
  13816. return BfTypedValue(mBfIRBuilder->CreateConstAggCE(mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs), dbgVar.mType,
  13817. dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  13818. }
  13819. }
  13820. return BfTypedValue();
  13821. }
  13822. auto useMethodState = mCurMethodState;
  13823. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13824. {
  13825. useMethodState = useMethodState->mPrevMethodState;
  13826. }
  13827. if (useMethodState != NULL)
  13828. {
  13829. // Fake a 'this' for var field resolution
  13830. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  13831. {
  13832. auto thisType = mCurTypeInstance;
  13833. if (thisType->IsValueType())
  13834. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  13835. else
  13836. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  13837. }
  13838. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  13839. {
  13840. return BfTypedValue();
  13841. }
  13842. }
  13843. else
  13844. {
  13845. //TODO: Do we allow useMethodState to be NULL anymore?
  13846. return BfTypedValue();
  13847. }
  13848. // Check mixin state for 'this'
  13849. {
  13850. auto checkMethodState = mCurMethodState;
  13851. while (checkMethodState != NULL)
  13852. {
  13853. if (checkMethodState->mMixinState != NULL)
  13854. {
  13855. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  13856. if (thisValue.HasType())
  13857. {
  13858. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13859. if (!thisValue.mType->IsValueType())
  13860. thisValue = LoadValue(thisValue);
  13861. return thisValue;
  13862. }
  13863. }
  13864. checkMethodState = checkMethodState->mPrevMethodState;
  13865. }
  13866. }
  13867. auto curMethodInstance = mCurMethodInstance;
  13868. if (useMethodState->mMethodInstance != NULL)
  13869. curMethodInstance = useMethodState->mMethodInstance;
  13870. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  13871. {
  13872. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  13873. {
  13874. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  13875. if (constLocal.mIsThis)
  13876. {
  13877. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  13878. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  13879. }
  13880. }
  13881. return BfTypedValue();
  13882. }
  13883. if (useMethodState->mLocals.IsEmpty())
  13884. {
  13885. // 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
  13886. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  13887. return BfTypedValue();
  13888. }
  13889. auto thisLocal = useMethodState->mLocals[0];
  13890. BF_ASSERT(thisLocal->mIsThis);
  13891. bool preferValue = !IsTargetingBeefBackend();
  13892. if (!thisLocal->mAddr)
  13893. preferValue = true;
  13894. bool usedVal = false;
  13895. BfIRValue thisValue;
  13896. if ((preferValue) && (!thisLocal->mIsLowered))
  13897. {
  13898. thisValue = thisLocal->mValue;
  13899. usedVal = true;
  13900. }
  13901. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  13902. thisValue = thisLocal->mAddr;
  13903. else
  13904. thisValue = mBfIRBuilder->CreateAlignedLoad(thisLocal->mAddr, thisLocal->mResolvedType->mAlign);
  13905. if (markUsing)
  13906. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13907. if (useMethodState->mClosureState != NULL)
  13908. {
  13909. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  13910. if (closureTypeInst != NULL)
  13911. {
  13912. if (closureTypeInst->mFieldInstances.size() > 0)
  13913. {
  13914. auto& field = closureTypeInst->mFieldInstances[0];
  13915. auto fieldDef = field.GetFieldDef();
  13916. if (fieldDef->mName == "__this")
  13917. {
  13918. if (mCurMethodState->mClosureState->mCapturing)
  13919. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  13920. // This is a captured 'this'
  13921. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  13922. if (field.mResolvedType->IsRef())
  13923. {
  13924. auto refType = (BfRefType*)field.mResolvedType;
  13925. auto underlyingType = refType->GetUnderlyingType();
  13926. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  13927. }
  13928. if (field.mResolvedType->IsObject())
  13929. {
  13930. result = LoadValue(result);
  13931. result.mKind = BfTypedValueKind_ThisValue;
  13932. }
  13933. else
  13934. {
  13935. if (fieldDef->mIsReadOnly)
  13936. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  13937. else
  13938. result.mKind = BfTypedValueKind_ThisAddr;
  13939. }
  13940. return result;
  13941. }
  13942. }
  13943. return BfTypedValue();
  13944. }
  13945. if (useMethodState->mClosureState->mCapturing)
  13946. {
  13947. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  13948. if (thisType->IsValueType())
  13949. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  13950. else
  13951. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  13952. }
  13953. }
  13954. if (mCurMethodInstance == NULL)
  13955. return BfTypedValue();
  13956. auto localDef = useMethodState->mLocals[0];
  13957. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  13958. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  13959. {
  13960. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating) && (!mCurMethodInstance->ForcingThisPtr()))
  13961. {
  13962. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  13963. }
  13964. if (localDef->mIsSplat)
  13965. {
  13966. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  13967. }
  13968. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  13969. }
  13970. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  13971. }
  13972. BfLocalVariable* BfModule::GetThisVariable()
  13973. {
  13974. if (mCurMethodState == NULL)
  13975. return NULL;
  13976. auto methodState = mCurMethodState->GetNonCaptureState();
  13977. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  13978. return methodState->mLocals[0];
  13979. return NULL;
  13980. }
  13981. bool BfModule::IsInGeneric()
  13982. {
  13983. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  13984. }
  13985. bool BfModule::InDefinitionSection()
  13986. {
  13987. if (mCurTypeInstance != NULL)
  13988. {
  13989. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  13990. return false;
  13991. }
  13992. return !IsInSpecializedSection();
  13993. }
  13994. bool BfModule::IsInSpecializedGeneric()
  13995. {
  13996. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  13997. return true;
  13998. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  13999. return false;
  14000. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  14001. }
  14002. bool BfModule::IsInSpecializedSection()
  14003. {
  14004. return IsInSpecializedGeneric() ||
  14005. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  14006. }
  14007. bool BfModule::IsInUnspecializedGeneric()
  14008. {
  14009. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  14010. return true;
  14011. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedType()))
  14012. return true;
  14013. return false;
  14014. }
  14015. //////////////////////////////////////////////////////////////////////////
  14016. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  14017. {
  14018. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  14019. if (type->IsValuelessType())
  14020. return mBfIRBuilder->GetFakeVal();
  14021. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  14022. if ((!doLifetimeEnd) && (WantsLifetimes()))
  14023. {
  14024. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  14025. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  14026. }
  14027. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  14028. auto typeOptions = GetTypeOptions();
  14029. if (typeOptions != NULL)
  14030. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  14031. // Local variable inits are implicitly handled in the Beef Backend
  14032. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  14033. {
  14034. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  14035. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  14036. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  14037. mBfIRBuilder->ClearDebugLocation(storeInst);
  14038. mBfIRBuilder->SetInsertPoint(prevBlock);
  14039. }
  14040. return allocaInst;
  14041. }
  14042. BfTypedValue BfModule::CreateOutVariable(BfAstNode* refNode, BfVariableDeclaration* variableDeclaration, BfAstNode* paramNameNode, BfType* variableType, BfTypedValue initValue)
  14043. {
  14044. bool isRef = false;
  14045. bool isLet = (variableDeclaration != NULL) && (variableDeclaration->mTypeRef->IsExact<BfLetTypeReference>());
  14046. bool isVar = (variableDeclaration == NULL) || (variableDeclaration->mTypeRef->IsExact<BfVarTypeReference>());
  14047. if (variableDeclaration != NULL)
  14048. {
  14049. if (auto varRefTypeReference = BfNodeDynCast<BfVarRefTypeReference>(variableDeclaration->mTypeRef))
  14050. {
  14051. isRef = true;
  14052. isLet = varRefTypeReference->mVarToken->GetToken() == BfToken_Let;
  14053. isVar = varRefTypeReference->mVarToken->GetToken() == BfToken_Var;
  14054. }
  14055. }
  14056. BfLocalVariable* localVar = new BfLocalVariable();
  14057. if ((variableDeclaration != NULL) && (variableDeclaration->mNameNode != NULL))
  14058. {
  14059. localVar->mName = variableDeclaration->mNameNode->ToString();
  14060. localVar->mNameNode = BfNodeDynCast<BfIdentifierNode>(variableDeclaration->mNameNode);
  14061. }
  14062. else
  14063. {
  14064. if (paramNameNode != NULL)
  14065. {
  14066. localVar->mName = "__";
  14067. paramNameNode->ToString(localVar->mName);
  14068. localVar->mName += "_";
  14069. localVar->mName += StrFormat("%d", mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  14070. }
  14071. else
  14072. localVar->mName = "__" + StrFormat("%d", mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  14073. }
  14074. localVar->mResolvedType = variableType;
  14075. if (isRef)
  14076. {
  14077. localVar->mResolvedType = CreateRefType(localVar->mResolvedType);
  14078. }
  14079. PopulateType(variableType);
  14080. if (!variableType->IsValuelessType())
  14081. localVar->mAddr = CreateAlloca(localVar->mResolvedType);
  14082. localVar->mIsReadOnly = isLet;
  14083. localVar->mReadFromId = 0;
  14084. localVar->mWrittenToId = 0;
  14085. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14086. CheckVariableDef(localVar);
  14087. localVar->Init();
  14088. AddLocalVariableDef(localVar, true);
  14089. BfExprEvaluator exprEvaluator(this);
  14090. exprEvaluator.CheckVariableDeclaration(refNode, false, false, false);
  14091. auto argValue = BfTypedValue(localVar->mAddr, CreateRefType(variableType, BfRefType::RefKind_Out));
  14092. if (isRef)
  14093. {
  14094. initValue = MakeAddressable(initValue, true, true);
  14095. if ((initValue) && (!initValue.mType->IsValuelessType()))
  14096. mBfIRBuilder->CreateStore(initValue.mValue, localVar->mAddr);
  14097. }
  14098. else
  14099. {
  14100. initValue = LoadOrAggregateValue(initValue);
  14101. if ((initValue) && (!initValue.mType->IsValuelessType()))
  14102. mBfIRBuilder->CreateStore(initValue.mValue, localVar->mAddr);
  14103. }
  14104. auto curScope = mCurMethodState->mCurScope;
  14105. if (curScope->mScopeKind == BfScopeKind_StatementTarget)
  14106. MoveLocalToParentScope(localVar);
  14107. return argValue;
  14108. }
  14109. void BfModule::MoveLocalToParentScope(BfLocalVariable* localVar)
  14110. {
  14111. auto curScope = mCurMethodState->mCurScope;
  14112. if (mCurMethodState->mLocals.back() != localVar)
  14113. return;
  14114. curScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  14115. if ((!curScope->mDeferredLifetimeEnds.IsEmpty()) && (curScope->mDeferredLifetimeEnds.back() == localVar->mAddr))
  14116. {
  14117. curScope->mDeferredLifetimeEnds.pop_back();
  14118. if (curScope->mPrevScope != NULL)
  14119. curScope->mPrevScope->mDeferredLifetimeEnds.push_back(localVar->mAddr);
  14120. }
  14121. }
  14122. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  14123. {
  14124. BF_ASSERT(localVar->mResolvedType != NULL);
  14125. while (localVar->mName.StartsWith('@'))
  14126. {
  14127. localVar->mNamePrefixCount++;
  14128. localVar->mName.Remove(0);
  14129. }
  14130. if (mCurMethodState->mLocals.mAllocSize == 0)
  14131. {
  14132. mCurMethodState->mLocals.Reserve(16);
  14133. mCurMethodState->mLocalVarSet.Reserve(16);
  14134. }
  14135. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  14136. mCurMethodState->mLocals.push_back(localVar);
  14137. BfLocalVarEntry* localVarEntryPtr;
  14138. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  14139. {
  14140. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  14141. localVarEntryPtr->mLocalVar = localVar;
  14142. }
  14143. }
  14144. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  14145. {
  14146. if (localVarDef->mResolvedType->IsVar())
  14147. return;
  14148. if ((mBfIRBuilder->DbgHasInfo()) &&
  14149. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  14150. (mHasFullDebugInfo) &&
  14151. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  14152. {
  14153. auto varType = localVarDef->mResolvedType;
  14154. if (localVarDef->mResolvedType->IsValuelessType())
  14155. {
  14156. }
  14157. else
  14158. {
  14159. bool isByAddr = false;
  14160. auto diValue = localVarDef->mValue;
  14161. if (localVarDef->mConstValue)
  14162. diValue = localVarDef->mConstValue;
  14163. else if (localVarDef->mAddr)
  14164. {
  14165. diValue = localVarDef->mAddr;
  14166. isByAddr = true;
  14167. }
  14168. if (diValue.IsConst())
  14169. {
  14170. auto constant = mBfIRBuilder->GetConstant(diValue);
  14171. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  14172. {
  14173. // Ignore for now
  14174. return;
  14175. }
  14176. }
  14177. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  14178. bool didConstToMem = false;
  14179. bool isConstant = false;
  14180. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  14181. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14182. else if (localVarDef->mConstValue)
  14183. {
  14184. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  14185. isConstant =
  14186. (constant->mConstType < BfConstType_GlobalVar) ||
  14187. (constant->mConstType == BfConstType_AggZero) ||
  14188. (constant->mConstType == BfConstType_Agg);
  14189. if (isConstant)
  14190. {
  14191. if (localVarDef->mResolvedType->IsComposite())
  14192. {
  14193. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  14194. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  14195. // if (IsTargetingBeefBackend())
  14196. // {
  14197. // diValue = mBfIRBuilder->CreateAliasValue(constMem);
  14198. // didConstToMem = true;
  14199. //
  14200. // diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14201. // }
  14202. //else
  14203. {
  14204. isByAddr = true;
  14205. mBfIRBuilder->SaveDebugLocation();
  14206. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  14207. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  14208. mBfIRBuilder->ClearDebugLocation();
  14209. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  14210. auto addrVal = CreateAlloca(ptrType);
  14211. mBfIRBuilder->CreateStore(constMem, addrVal);
  14212. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14213. diValue = addrVal;
  14214. didConstToMem = true;
  14215. mBfIRBuilder->SetInsertPoint(prevBlock);
  14216. mBfIRBuilder->RestoreDebugLocation();
  14217. }
  14218. }
  14219. if (mCompiler->mOptions.IsCodeView())
  14220. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14221. }
  14222. }
  14223. if (!mBfIRBuilder->mIgnoreWrites)
  14224. {
  14225. if ((localVarDef->mIsStatic) && (localVarDef->mAddr) && (!localVarDef->mResolvedType->IsValuelessType()))
  14226. {
  14227. auto refType = CreateRefType(localVarDef->mResolvedType);
  14228. diType = mBfIRBuilder->DbgGetType(refType);
  14229. auto refAlloca = CreateAlloca(refType);
  14230. mBfIRBuilder->CreateStore(localVarDef->mAddr, refAlloca);
  14231. diValue = refAlloca;
  14232. }
  14233. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14234. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  14235. localVarDef->mDbgVarInst = diVariable;
  14236. if (mBfIRBuilder->HasDebugLocation())
  14237. {
  14238. if ((isConstant) && (!didConstToMem))
  14239. {
  14240. BfTypedValue result(localVarDef->mConstValue, localVarDef->mResolvedType);
  14241. FixValueActualization(result);
  14242. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(result.mValue, diVariable);
  14243. }
  14244. else
  14245. {
  14246. if ((IsTargetingBeefBackend()) && (doAliasValue) && (!mIsComptimeModule))
  14247. {
  14248. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  14249. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  14250. }
  14251. if (isByAddr)
  14252. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  14253. else if (diValue)
  14254. {
  14255. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  14256. }
  14257. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  14258. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14259. }
  14260. }
  14261. }
  14262. }
  14263. }
  14264. }
  14265. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  14266. {
  14267. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  14268. {
  14269. if ((!localVarDef->mValue.IsConst()) &&
  14270. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  14271. {
  14272. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  14273. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  14274. }
  14275. }
  14276. if (addDebugInfo)
  14277. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  14278. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  14279. DoAddLocalVariable(localVarDef);
  14280. auto rootMethodState = mCurMethodState->GetRootMethodState();
  14281. if (localVarDef->mLocalVarId == -1)
  14282. {
  14283. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  14284. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  14285. }
  14286. bool checkLocal = true;
  14287. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  14288. {
  14289. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(mCurMethodInstance->mMethodDef->mMethodDeclaration))
  14290. checkLocal = false;
  14291. }
  14292. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!mIsComptimeModule) && (checkLocal))
  14293. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  14294. if (((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL)) && (checkLocal))
  14295. {
  14296. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  14297. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL) && (rootMethodState->mMethodInstance != NULL) && (!mIsComptimeModule))
  14298. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  14299. }
  14300. return localVarDef;
  14301. }
  14302. void BfModule::CreateDIRetVal()
  14303. {
  14304. if (!WantsDebugInfo())
  14305. return;
  14306. /*if (!mCurMethodState->mRetVal)
  14307. {
  14308. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  14309. return;
  14310. }*/
  14311. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  14312. {
  14313. BfType* dbgType = mCurMethodInstance->mReturnType;
  14314. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  14315. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14316. {
  14317. BF_ASSERT(mCurMethodState->mRetValAddr);
  14318. dbgType = CreatePointerType(dbgType);
  14319. dbgValue = mCurMethodState->mRetValAddr;
  14320. }
  14321. else
  14322. {
  14323. BF_ASSERT(!mCurMethodState->mRetValAddr);
  14324. }
  14325. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14326. "@return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  14327. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  14328. }
  14329. }
  14330. BfTypedValue BfModule::CreateTuple(const Array<BfTypedValue>& values, const Array<String>& fieldNames)
  14331. {
  14332. BfTypeVector fieldTypes;
  14333. for (auto arg : values)
  14334. fieldTypes.Add(arg.mType);
  14335. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  14336. auto tupleTypedValue = BfTypedValue(CreateAlloca(tupleType), tupleType, true);
  14337. for (int fieldIdx = 0; fieldIdx < tupleType->mFieldInstances.size(); fieldIdx++)
  14338. {
  14339. auto& fieldInstance = tupleType->mFieldInstances[fieldIdx];
  14340. if (fieldInstance.mDataIdx <= 0)
  14341. continue;
  14342. auto typedVal = values[fieldIdx];
  14343. typedVal = LoadOrAggregateValue(typedVal);
  14344. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, mBfIRBuilder->CreateInBoundsGEP(tupleTypedValue.mValue, 0, fieldInstance.mDataIdx), typedVal.mType->mAlign);
  14345. }
  14346. return tupleTypedValue;
  14347. }
  14348. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  14349. {
  14350. if (variableDef->mName.IsEmpty())
  14351. return;
  14352. BfLocalVarEntry* localVarEntryPtr = NULL;
  14353. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  14354. {
  14355. auto checkLocal = localVarEntryPtr->mLocalVar;
  14356. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  14357. {
  14358. auto _Fail = [&](int warningNum, String str, BfAstNode* refNode)
  14359. {
  14360. BfError* error = Warn(warningNum, str, refNode);
  14361. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  14362. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  14363. };
  14364. auto checkScope = mCurMethodState->mCurScope;
  14365. if (checkScope->mScopeKind == BfScopeKind_StatementTarget)
  14366. checkScope = checkScope->mPrevScope;
  14367. if (checkLocal->mIsImplicitParam)
  14368. return; // Ignore 'redefinition'
  14369. if (checkLocal->IsParam())
  14370. {
  14371. if (variableDef->IsParam())
  14372. _Fail(4200, StrFormat("A parameter named '%s' has already been declared", variableDef->mName.c_str()), variableDef->mNameNode);
  14373. else
  14374. _Fail(4200, 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);
  14375. }
  14376. else if (checkLocal->mLocalVarIdx < checkScope->mLocalVarStart)
  14377. _Fail(4200, StrFormat("A variable named '%s' has already been declared in an outer scope", variableDef->mName.c_str()), variableDef->mNameNode);
  14378. else
  14379. _Fail(4200, StrFormat("A variable named '%s' has already been declared in this scope", variableDef->mName.c_str()), variableDef->mNameNode);
  14380. return;
  14381. }
  14382. }
  14383. }
  14384. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  14385. {
  14386. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  14387. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  14388. {
  14389. if ((tokenNode->GetToken() == BfToken_Colon) || (tokenNode->GetToken() == BfToken_ColonColon))
  14390. {
  14391. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  14392. {
  14393. Fail("Cannot access method scope across deferred block boundary", scopeName);
  14394. return NULL;
  14395. }
  14396. return &mCurMethodState->mHeadScope;
  14397. }
  14398. else if (tokenNode->GetToken() == BfToken_Mixin)
  14399. {
  14400. if (fromMixinState == NULL)
  14401. {
  14402. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  14403. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  14404. return mCurMethodState->mCurScope;
  14405. }
  14406. fromMixinState->mUsedInvocationScope = true;
  14407. return fromMixinState->mTargetScope;
  14408. }
  14409. else if (tokenNode->GetToken() == BfToken_New)
  14410. return NULL;
  14411. }
  14412. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  14413. {
  14414. auto findLabel = scopeName->ToString();
  14415. bool crossedDeferredBlock = false;
  14416. auto checkScope = mCurMethodState->mCurScope;
  14417. while (checkScope != NULL)
  14418. {
  14419. if (checkScope->mIsDeferredBlock)
  14420. crossedDeferredBlock = true;
  14421. if (checkScope->mLabel == findLabel)
  14422. {
  14423. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  14424. {
  14425. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  14426. return NULL;
  14427. }
  14428. return checkScope;
  14429. }
  14430. checkScope = checkScope->mPrevScope;
  14431. }
  14432. if (!inMixinDecl)
  14433. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  14434. return NULL;
  14435. }
  14436. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  14437. {
  14438. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  14439. }
  14440. return mCurMethodState->mCurScope;
  14441. }
  14442. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  14443. {
  14444. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  14445. }
  14446. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  14447. {
  14448. auto scopeData = FindScope(scopeName, false);
  14449. if (scopeData == NULL)
  14450. return NULL;
  14451. int scopeDepth = scopeData->GetDepth();
  14452. // Find the first break data that is at or below the depth of our requested scope
  14453. auto breakData = mCurMethodState->mBreakData;
  14454. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  14455. {
  14456. if (breakData->mScope->mIsConditional)
  14457. return NULL;
  14458. breakData = breakData->mPrevBreakData;
  14459. }
  14460. return breakData;
  14461. }
  14462. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  14463. {
  14464. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  14465. if (!IsTargetingBeefBackend())
  14466. return;
  14467. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  14468. {
  14469. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14470. }
  14471. }
  14472. void BfModule::ClearLifetimeEnds()
  14473. {
  14474. auto scopeData = mCurMethodState->mCurScope;
  14475. while (scopeData != NULL)
  14476. {
  14477. scopeData->mDeferredLifetimeEnds.Clear();
  14478. scopeData = scopeData->mPrevScope;
  14479. }
  14480. }
  14481. bool BfModule::WantsDebugInfo()
  14482. {
  14483. if ((mCurMethodInstance != NULL) &&
  14484. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  14485. return false;
  14486. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  14487. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  14488. }
  14489. BfTypeOptions* BfModule::GetTypeOptions()
  14490. {
  14491. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  14492. return mCurMethodState->mMethodTypeOptions;
  14493. if (mCurMethodInstance == NULL)
  14494. return NULL;
  14495. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  14496. }
  14497. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  14498. {
  14499. BfReflectKind reflectKind = BfReflectKind_None;
  14500. if (attrType->mCustomAttributes != NULL)
  14501. {
  14502. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  14503. {
  14504. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  14505. {
  14506. for (auto& prop : customAttr.mSetProperties)
  14507. {
  14508. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  14509. if (propDef->mName == "ReflectUser")
  14510. {
  14511. if (prop.mParam.mValue.IsConst())
  14512. {
  14513. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  14514. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  14515. }
  14516. }
  14517. }
  14518. // Check for Flags arg
  14519. if (customAttr.mCtorArgs.size() < 2)
  14520. continue;
  14521. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  14522. if (constant == NULL)
  14523. continue;
  14524. if (constant->mTypeCode == BfTypeCode_Boolean)
  14525. continue;
  14526. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  14527. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  14528. }
  14529. }
  14530. }
  14531. return reflectKind;
  14532. }
  14533. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  14534. {
  14535. auto checkTypeInstance = typeInstance;
  14536. while (checkTypeInstance != NULL)
  14537. {
  14538. if (checkTypeInstance->mCustomAttributes != NULL)
  14539. {
  14540. auto checkReflectKind = BfReflectKind_None;
  14541. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  14542. {
  14543. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  14544. {
  14545. if (customAttr.mCtorArgs.size() > 0)
  14546. {
  14547. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  14548. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  14549. }
  14550. else
  14551. {
  14552. checkReflectKind = BfReflectKind_All;
  14553. }
  14554. }
  14555. else
  14556. {
  14557. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  14558. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  14559. }
  14560. }
  14561. if ((checkTypeInstance == typeInstance) ||
  14562. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  14563. {
  14564. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  14565. }
  14566. }
  14567. for (auto ifaceEntry : typeInstance->mInterfaces)
  14568. {
  14569. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  14570. {
  14571. auto iface = ifaceEntry.mInterfaceType;
  14572. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  14573. if (customAttr != NULL)
  14574. {
  14575. for (auto& prop : customAttr->mSetProperties)
  14576. {
  14577. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  14578. if (propDef->mName == "ReflectImplementer")
  14579. {
  14580. if (prop.mParam.mValue.IsConst())
  14581. {
  14582. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  14583. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  14584. }
  14585. }
  14586. }
  14587. }
  14588. }
  14589. }
  14590. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  14591. }
  14592. return reflectKind;
  14593. }
  14594. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  14595. {
  14596. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14597. while (checkScope != NULL)
  14598. {
  14599. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  14600. return true;
  14601. if (checkScope == scope)
  14602. break;
  14603. checkScope = checkScope->mPrevScope;
  14604. }
  14605. return false;
  14606. }
  14607. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  14608. {
  14609. // Is there anything we need to do here?
  14610. if (mBfIRBuilder->mIgnoreWrites)
  14611. {
  14612. // Just visit deferred blocks
  14613. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14614. while (checkScope != NULL)
  14615. {
  14616. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14617. while (deferredCallEntry != NULL)
  14618. {
  14619. if (deferredCallEntry->mDeferredBlock != NULL)
  14620. {
  14621. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14622. if (checkScope == &mCurMethodState->mHeadScope)
  14623. CreateRetValLocal();
  14624. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry->mEmitRefNode);
  14625. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  14626. }
  14627. deferredCallEntry = deferredCallEntry->mNext;
  14628. }
  14629. if (checkScope == scopeData)
  14630. break;
  14631. checkScope = checkScope->mPrevScope;
  14632. }
  14633. return;
  14634. }
  14635. // Why did we want to do SetIllegalSrcPos here?
  14636. // Don't we always want to step onto these instances?
  14637. // Find a case where we don't and perhaps only do it there.
  14638. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  14639. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  14640. //SetIllegalSrcPos();
  14641. bool setSrcPos = false;
  14642. bool wantsNop = true;
  14643. BfAstNode* deferCloseNode = NULL;
  14644. if (mCurMethodState->mInPostReturn)
  14645. {
  14646. // These won't get used, they are post-return
  14647. return;
  14648. }
  14649. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  14650. BfScopeData* scopeJumpBlock = NULL;
  14651. bool hadExtraDeferredLifetimeEnds = false;
  14652. auto _FlushLifetimeEnds = [&]()
  14653. {
  14654. for (auto lifetimeEnd : deferredLifetimeEnds)
  14655. {
  14656. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14657. mBfIRBuilder->ClearDebugLocation_Last();
  14658. }
  14659. deferredLifetimeEnds.clear();
  14660. };
  14661. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14662. while (checkScope != NULL)
  14663. {
  14664. if (checkScope->mCloseNode != NULL)
  14665. deferCloseNode = checkScope->mCloseNode;
  14666. if (doneBlock)
  14667. {
  14668. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  14669. for (auto& checkHandler : checkScope->mDeferredHandlers)
  14670. {
  14671. if (checkHandler.mDoneBlock == doneBlock)
  14672. {
  14673. scopeJumpBlock = checkScope;
  14674. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  14675. mBfIRBuilder->ClearDebugLocation_Last();
  14676. _FlushLifetimeEnds();
  14677. break;
  14678. }
  14679. }
  14680. if (scopeJumpBlock != NULL)
  14681. break;
  14682. }
  14683. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  14684. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  14685. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  14686. if (hasWork)
  14687. {
  14688. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  14689. if (deferCloseNode != NULL)
  14690. {
  14691. UpdateSrcPos(deferCloseNode);
  14692. }
  14693. if (checkScope == &mCurMethodState->mHeadScope)
  14694. CreateRetValLocal();
  14695. if (doneBlock)
  14696. {
  14697. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  14698. String blockName = "deferredCalls";
  14699. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  14700. BfDeferredHandler deferredHandler;
  14701. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  14702. {
  14703. mBfIRBuilder->SaveDebugLocation();
  14704. mBfIRBuilder->ClearDebugLocation();
  14705. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  14706. mBfIRBuilder->RestoreDebugLocation();
  14707. }
  14708. else
  14709. {
  14710. // Definitely chain
  14711. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  14712. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  14713. mBfIRBuilder->ClearDebugLocation_Last();
  14714. _FlushLifetimeEnds();
  14715. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  14716. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  14717. }
  14718. deferredHandler.mDoneBlock = doneBlock;
  14719. if (!mBfIRBuilder->mIgnoreWrites)
  14720. checkScope->mDeferredHandlers.push_back(deferredHandler);
  14721. if (checkScope == &mCurMethodState->mHeadScope)
  14722. {
  14723. if (!mCurMethodState->mDIRetVal)
  14724. {
  14725. // 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
  14726. // be scoped to the physical method
  14727. /*if (deferCloseNode != NULL)
  14728. {
  14729. UpdateSrcPos(deferCloseNode);
  14730. }*/
  14731. CreateDIRetVal();
  14732. }
  14733. }
  14734. if (checkScope != mCurMethodState->mTailScope)
  14735. {
  14736. if (deferredHandler.mHandlerBlock.IsFake())
  14737. {
  14738. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14739. }
  14740. if (!mBfIRBuilder->mIgnoreWrites)
  14741. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  14742. }
  14743. }
  14744. HashSet<BfDeferredCallEntry*> handledSet;
  14745. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14746. while (deferredCallEntry != NULL)
  14747. {
  14748. BfDeferredCallEmitState deferredCallEmitState;
  14749. deferredCallEmitState.mCloseNode = deferCloseNode;
  14750. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  14751. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  14752. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14753. if (deferCloseNode != NULL)
  14754. {
  14755. UpdateSrcPos(deferCloseNode);
  14756. }
  14757. if (wantsNop)
  14758. EmitEnsureInstructionAt();
  14759. wantsNop = false;
  14760. if (deferredCallEntry->mDeferredBlock != NULL)
  14761. {
  14762. BfDeferredCallEntry** entryPtr = NULL;
  14763. if (!handledSet.TryAdd(deferredCallEntry, &entryPtr))
  14764. {
  14765. // Already handled, can happen if we defer again within the block
  14766. deferredCallEntry = deferredCallEntry->mNext;
  14767. continue;
  14768. }
  14769. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  14770. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14771. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  14772. {
  14773. // The list changed, start over and ignore anything we've already handled
  14774. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14775. }
  14776. else
  14777. deferredCallEntry = deferredCallEntry->mNext;
  14778. }
  14779. else
  14780. {
  14781. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14782. deferredCallEntry = deferredCallEntry->mNext;
  14783. }
  14784. }
  14785. if (checkScope->mSavedStack)
  14786. {
  14787. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  14788. if (mCurMethodState->mDynStackRevIdx)
  14789. {
  14790. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  14791. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  14792. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  14793. }
  14794. }
  14795. }
  14796. if (!checkScope->mIsScopeHead)
  14797. {
  14798. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  14799. if (!IsTargetingBeefBackend())
  14800. {
  14801. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14802. {
  14803. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14804. }
  14805. }
  14806. else
  14807. {
  14808. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14809. {
  14810. deferredLifetimeEnds.Add(lifetimeEnd);
  14811. }
  14812. }
  14813. }
  14814. if (checkScope == scopeData)
  14815. break;
  14816. checkScope = checkScope->mPrevScope;
  14817. }
  14818. if ((doneBlock) && (scopeJumpBlock == NULL))
  14819. {
  14820. mBfIRBuilder->CreateBr(doneBlock);
  14821. mBfIRBuilder->ClearDebugLocation_Last();
  14822. }
  14823. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  14824. // may have been created when other scope lifetimes were available
  14825. _FlushLifetimeEnds();
  14826. // Emit lifetimeEnds after the branch for Beef
  14827. /*if (IsTargetingBeefBackend())
  14828. {
  14829. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  14830. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14831. while (checkScope != NULL)
  14832. {
  14833. if (checkScope == scopeJumpBlock)
  14834. break;
  14835. if (!checkScope->mIsScopeHead)
  14836. {
  14837. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14838. {
  14839. if (needsEnsureInst)
  14840. {
  14841. needsEnsureInst = false;
  14842. }
  14843. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14844. }
  14845. }
  14846. if (checkScope == scopeData)
  14847. break;
  14848. checkScope = checkScope->mPrevScope;
  14849. }
  14850. }*/
  14851. }
  14852. void BfModule::MarkScopeLeft(BfScopeData* scopeData, bool isNoReturn)
  14853. {
  14854. if ((mCurMethodState->mDeferredLocalAssignData != NULL) && (!isNoReturn))
  14855. {
  14856. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  14857. while (deferredLocalAssignData != NULL)
  14858. {
  14859. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  14860. break;
  14861. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  14862. deferredLocalAssignData->mIsUnconditional = false;
  14863. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  14864. }
  14865. }
  14866. // When we leave a scope, mark those as assigned for deferred assignment purposes
  14867. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  14868. {
  14869. auto localDef = mCurMethodState->mLocals[localIdx];
  14870. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  14871. {
  14872. bool hadAssignment = false;
  14873. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  14874. {
  14875. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  14876. if (entry.mLocalVar == localDef)
  14877. hadAssignment = true;
  14878. }
  14879. if (!hadAssignment)
  14880. {
  14881. if (!isNoReturn)
  14882. localDef->mHadExitBeforeAssign = true;
  14883. mCurMethodState->LocalDefined(localDef);
  14884. }
  14885. }
  14886. }
  14887. }
  14888. void BfModule::CreateReturn(BfIRValue val)
  14889. {
  14890. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14891. {
  14892. // Store to sret
  14893. BF_ASSERT(val);
  14894. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14895. mBfIRBuilder->CreateRetVoid();
  14896. return;
  14897. }
  14898. if (mCurMethodInstance->mReturnType->IsVar())
  14899. return;
  14900. if (mCurMethodInstance->mReturnType->IsValuelessType())
  14901. {
  14902. mBfIRBuilder->CreateRetVoid();
  14903. return;
  14904. }
  14905. if (mCurMethodInstance->mReturnType->IsStruct())
  14906. {
  14907. BfTypeCode loweredReturnType = BfTypeCode_None;
  14908. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  14909. if (!mIsComptimeModule)
  14910. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  14911. if (loweredReturnType != BfTypeCode_None)
  14912. {
  14913. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  14914. mBfIRBuilder->CreateStore(val, retVal);
  14915. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  14916. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  14917. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  14918. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  14919. mBfIRBuilder->CreateRet(loadedReturnValue);
  14920. return;
  14921. }
  14922. }
  14923. BF_ASSERT(val);
  14924. mBfIRBuilder->CreateRet(val);
  14925. }
  14926. void BfModule::EmitReturn(const BfTypedValue& val)
  14927. {
  14928. if (mCurMethodState->mIRExitBlock)
  14929. {
  14930. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  14931. {
  14932. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  14933. {
  14934. if ((mCurMethodState->mRetValAddr) || (mCurMethodState->mRetVal))
  14935. {
  14936. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  14937. if (!mCurMethodState->mRetVal)
  14938. retVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetValAddr, mCurMethodInstance->mReturnType->mAlign);
  14939. mBfIRBuilder->CreateAlignedStore(val.mValue, retVal, mCurMethodInstance->mReturnType->mAlign);
  14940. }
  14941. else if (mIsComptimeModule)
  14942. {
  14943. mBfIRBuilder->PopulateType(val.mType);
  14944. if (!val.mType->IsValuelessType())
  14945. mBfIRBuilder->CreateSetRet(val.mValue, val.mType->mTypeId);
  14946. else
  14947. mBfIRBuilder->CreateSetRet(BfIRValue(), val.mType->mTypeId);
  14948. }
  14949. else
  14950. {
  14951. // Just ignore
  14952. BF_ASSERT(mCurMethodInstance->mReturnType->IsVar());
  14953. }
  14954. }
  14955. }
  14956. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14957. }
  14958. else
  14959. {
  14960. EmitDeferredScopeCalls(false, NULL);
  14961. if (val)
  14962. {
  14963. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14964. }
  14965. }
  14966. mCurMethodState->SetHadReturn(true);
  14967. mCurMethodState->mLeftBlockUncond = true;
  14968. }
  14969. void BfModule::EmitDefaultReturn()
  14970. {
  14971. if (mCurMethodState->mInDeferredBlock)
  14972. return;
  14973. if (mCurMethodState->mIRExitBlock)
  14974. {
  14975. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14976. }
  14977. else
  14978. {
  14979. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mReturnType->IsVar()))
  14980. {
  14981. // Ignore
  14982. }
  14983. else if (mCurMethodInstance->mReturnType->IsVoid())
  14984. mBfIRBuilder->CreateRetVoid();
  14985. else if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == -1))
  14986. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  14987. }
  14988. mCurMethodState->SetHadReturn(true);
  14989. mCurMethodState->mLeftBlockUncond = true;
  14990. }
  14991. void BfModule::AssertErrorState()
  14992. {
  14993. if (mIgnoreErrors)
  14994. return;
  14995. if (mHadBuildError)
  14996. return;
  14997. if (mCurTypeInstance != NULL)
  14998. {
  14999. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  15000. return;
  15001. }
  15002. if (mCurMethodInstance != NULL)
  15003. {
  15004. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  15005. return;
  15006. if (mCurMethodInstance->mHasFailed)
  15007. return;
  15008. }
  15009. // We want the module to be marked as failed even if it's just an error in the parser
  15010. if (mCurMethodInstance != NULL)
  15011. mCurMethodInstance->mHasFailed = true;
  15012. mHadBuildError = true;
  15013. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  15014. if (mCurTypeInstance != NULL)
  15015. {
  15016. if (mCurTypeInstance->mTypeFailed)
  15017. return;
  15018. if ((mCurTypeInstance->mTypeDef->GetDefinition()->mSource != NULL) && (mCurTypeInstance->mTypeDef->GetDefinition()->mSource->mParsingFailed))
  15019. return;
  15020. }
  15021. if (mCurMethodInstance != NULL)
  15022. {
  15023. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) &&
  15024. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  15025. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  15026. return;
  15027. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) &&
  15028. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  15029. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  15030. return;
  15031. }
  15032. if (mCompiler->IsAutocomplete())
  15033. return;
  15034. if (mCompiler->mPassInstance->HasFailed())
  15035. return;
  15036. InternalError("Compiler in invalid state but AssertErrorState failed to detect prior error");
  15037. }
  15038. void BfModule::AssertParseErrorState()
  15039. {
  15040. if (mCompiler->mRevision == 1)
  15041. AssertErrorState();
  15042. }
  15043. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  15044. {
  15045. BF_ASSERT(delegateType->IsDelegateOrFunction());
  15046. auto typeInst = delegateType->ToTypeInstance();
  15047. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  15048. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  15049. if (invokeMethodInstance == NULL)
  15050. return GetPrimitiveType(BfTypeCode_Var);
  15051. return invokeMethodInstance->mReturnType;
  15052. }
  15053. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  15054. {
  15055. if (typeInstance->IsClosure())
  15056. typeInstance = typeInstance->mBaseType;
  15057. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  15058. }
  15059. String BfModule::GetDelegateSignatureString(BfTypeInstance* typeInstance)
  15060. {
  15061. auto invokeMethod = GetDelegateInvokeMethod(typeInstance);
  15062. if (invokeMethod == NULL)
  15063. return "";
  15064. String sigString = "";
  15065. sigString = TypeToString(invokeMethod->mReturnType);
  15066. sigString += "(";
  15067. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  15068. {
  15069. if (paramIdx > 0)
  15070. sigString += ", ";
  15071. auto paramKind = invokeMethod->GetParamKind(paramIdx);
  15072. if (paramKind == BfParamKind_Params)
  15073. {
  15074. sigString += "params ";
  15075. }
  15076. auto paramType = invokeMethod->GetParamType(paramIdx);
  15077. sigString += TypeToString(paramType);
  15078. if (paramKind == BfParamKind_ExplicitThis)
  15079. sigString += " this";
  15080. }
  15081. sigString += ")";
  15082. return sigString;
  15083. }
  15084. int BfModule::GetSignatureId(const StringImpl& str)
  15085. {
  15086. int strId = mContext->GetStringLiteralId(str);
  15087. mSignatureIdRefs.Add(strId);
  15088. return strId;
  15089. }
  15090. int BfModule::GetDelegateSignatureId(BfTypeInstance* typeInstance)
  15091. {
  15092. BF_ASSERT(typeInstance->IsDelegate());
  15093. if (typeInstance->mTypeInfoEx == NULL)
  15094. {
  15095. typeInstance->mTypeInfoEx = new BfTypeInfoEx();
  15096. auto signature = GetDelegateSignatureString(typeInstance);
  15097. typeInstance->mTypeInfoEx->mMinValue = GetSignatureId(signature);
  15098. }
  15099. return (int)typeInstance->mTypeInfoEx->mMinValue;
  15100. }
  15101. void BfModule::CreateDelegateInvokeMethod()
  15102. {
  15103. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  15104. //mBfIRBuilder->ClearDebugLocation();
  15105. SetIllegalSrcPos();
  15106. auto typeInstance = mCurTypeInstance;
  15107. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  15108. SizedArray<BfIRType, 4> staticParamTypes;
  15109. SizedArray<BfIRValue, 4> staticFuncArgs;
  15110. SizedArray<BfIRValue, 4> memberFuncArgs;
  15111. auto multicastDelegateType = typeInstance->mBaseType;
  15112. if (multicastDelegateType->mFieldInstances.size() != 2)
  15113. {
  15114. AssertErrorState();
  15115. return;
  15116. }
  15117. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  15118. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  15119. auto fieldVal = mBfIRBuilder->CreateAlignedLoad(fieldPtr, mSystem->mPtrSize);
  15120. BfExprEvaluator exprEvaluator(this);
  15121. SizedArray<BfIRType, 8> origParamTypes;
  15122. BfIRType origReturnType;
  15123. BfIRType staticReturnType;
  15124. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  15125. if (mCurMethodInstance->mReturnType->IsValueType())
  15126. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  15127. if ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() != 0))
  15128. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  15129. int thisIdx = 0;
  15130. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  15131. {
  15132. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  15133. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  15134. }
  15135. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  15136. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  15137. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == 0))
  15138. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  15139. mCurMethodInstance->GetIRFunctionInfo(this, staticReturnType, staticParamTypes, true);
  15140. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  15141. {
  15142. if (mCurMethodState->mLocals[i]->mCompositeCount >= 0)
  15143. continue;
  15144. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  15145. exprEvaluator.PushArg(localVal, staticFuncArgs);
  15146. exprEvaluator.PushArg(localVal, memberFuncArgs);
  15147. }
  15148. auto staticFunc = mBfIRBuilder->CreateFunctionType(staticReturnType, staticParamTypes, false);
  15149. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  15150. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  15151. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  15152. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  15153. auto doneBB = mBfIRBuilder->CreateBlock("done");
  15154. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  15155. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  15156. BfIRValue nonStaticResult;
  15157. BfIRValue staticResult;
  15158. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  15159. auto trueEndBB = trueBB;
  15160. /// Non-static invocation
  15161. {
  15162. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  15163. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  15164. mBfIRBuilder->SetInsertPoint(trueBB);
  15165. BfIRValue numVal;
  15166. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule) && (mCompiler->mSystem->mPtrSize == 8))
  15167. {
  15168. numVal = mBfIRBuilder->CreatePtrToInt(fieldVal, BfTypeCode_UInt64);
  15169. auto andVal = mBfIRBuilder->CreateAnd(numVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)~0x8000000000000000ULL));
  15170. fieldVal = mBfIRBuilder->CreateIntToPtr(andVal, mBfIRBuilder->MapType(mContext->mBfObjectType));
  15171. }
  15172. if ((WantsObjectAccessCheck(mContext->mBfObjectType) && (mCompiler->mSystem->mPtrSize == 8)))
  15173. {
  15174. auto oacDoBB = mBfIRBuilder->CreateBlock("oac.do", true);
  15175. auto oacDoneBB = mBfIRBuilder->CreateBlock("oac.done");
  15176. auto checkGTE = mBfIRBuilder->CreateCmpGTE(numVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)0x8000000000000000ULL), false);
  15177. mBfIRBuilder->CreateCondBr(checkGTE, oacDoBB, oacDoneBB);
  15178. mBfIRBuilder->SetInsertPoint(oacDoBB);
  15179. mBfIRBuilder->CreateObjectAccessCheck(fieldVal, !IsOptimized());
  15180. mBfIRBuilder->CreateBr(oacDoneBB);
  15181. mBfIRBuilder->AddBlock(oacDoneBB);
  15182. mBfIRBuilder->SetInsertPoint(oacDoneBB);
  15183. trueEndBB = oacDoneBB;
  15184. }
  15185. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  15186. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  15187. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  15188. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  15189. BfExprEvaluator exprEvaluator(this);
  15190. BfTypedValue nonStaticTypedResult = exprEvaluator.CreateCall(NULL, mCurMethodInstance, funcPtr, true, memberFuncArgs, NULL, BfCreateCallFlags_DelegateThunkNonStatic);
  15191. nonStaticResult = nonStaticTypedResult.mValue;
  15192. mCurMethodState->SetHadReturn(false);
  15193. mCurMethodState->mLeftBlockUncond = false;
  15194. mCurMethodState->mLeftBlockCond = false;
  15195. mBfIRBuilder->CreateBr(doneBB);
  15196. }
  15197. // Static invocation
  15198. {
  15199. mBfIRBuilder->AddBlock(falseBB);
  15200. mBfIRBuilder->SetInsertPoint(falseBB);
  15201. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  15202. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  15203. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  15204. BfExprEvaluator exprEvaluator(this);
  15205. BfTypedValue staticTypedResult = exprEvaluator.CreateCall(NULL, mCurMethodInstance, funcPtr, true, staticFuncArgs, NULL, BfCreateCallFlags_DelegateThunkStatic);
  15206. staticResult = staticTypedResult.mValue;
  15207. // We had a sret for the non-static but no sret for the static (because we have a lowered return type there)
  15208. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1) && (mCurMethodInstance->GetStructRetIdx(true) == -1))
  15209. {
  15210. auto sretToType = mBfIRBuilder->GetPointerTo(staticReturnType);
  15211. auto sretCastedPtr = mBfIRBuilder->CreateBitCast(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), sretToType);
  15212. mBfIRBuilder->CreateStore(staticResult, sretCastedPtr);
  15213. }
  15214. mCurMethodState->SetHadReturn(false);
  15215. mCurMethodState->mLeftBlockUncond = false;
  15216. mCurMethodState->mLeftBlockCond = false;
  15217. mBfIRBuilder->CreateBr(doneBB);
  15218. }
  15219. mBfIRBuilder->AddBlock(doneBB);
  15220. mBfIRBuilder->SetInsertPoint(doneBB);
  15221. if (mCurMethodInstance->mReturnType->IsVar())
  15222. {
  15223. // Do nothing
  15224. }
  15225. else if ((mCurMethodInstance->mReturnType->IsValuelessType()) ||
  15226. ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1)))
  15227. {
  15228. mBfIRBuilder->CreateRetVoid();
  15229. }
  15230. else
  15231. {
  15232. BfIRType loweredIRReturnType;
  15233. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15234. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15235. if ((!mIsComptimeModule) && (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2)) && (loweredTypeCode != BfTypeCode_None))
  15236. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  15237. else
  15238. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  15239. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  15240. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueEndBB);
  15241. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  15242. mBfIRBuilder->CreateRet(phi);
  15243. }
  15244. }
  15245. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  15246. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  15247. {
  15248. auto typeDef = typeInstance->mTypeDef;
  15249. auto methodDeclaration = methodDef->mMethodDeclaration;
  15250. if (!mCompiler->mIsResolveOnly)
  15251. return true;
  15252. if (typeInstance->IsGenericTypeInstance())
  15253. {
  15254. // We only really want to process the unspecialized type for autocompletion
  15255. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  15256. return false;
  15257. }
  15258. BfAstNode* checkNode = methodDeclaration;
  15259. if (methodDeclaration == NULL)
  15260. checkNode = methodDef->mBody;
  15261. if ((!mCompiler->mResolvePassData->mParsers.IsEmpty()) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParsers[0])))
  15262. {
  15263. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  15264. return true;
  15265. }
  15266. return false;
  15267. }
  15268. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  15269. {
  15270. methodInst->mAppendAllocAlign = 1;
  15271. }
  15272. BfAllowAppendKind BfModule::GetBaseAllowAppend(BfMethodInstance* curMethodInstance)
  15273. {
  15274. auto typeInstance = curMethodInstance->GetOwner();
  15275. auto methodDef = curMethodInstance->mMethodDef;
  15276. if (methodDef->mAppendKind == BfAllowAppendKind_No)
  15277. return BfAllowAppendKind_No;
  15278. if ((typeInstance->mInstSize == typeInstance->mBaseType->mInstSize) &&
  15279. (typeInstance->IsZeroGap()) &&
  15280. (typeInstance->mBaseType->IsZeroGap()) &&
  15281. (methodDef->mAppendKind == BfAllowAppendKind_ZeroGap))
  15282. {
  15283. return BfAllowAppendKind_ZeroGap;
  15284. }
  15285. return BfAllowAppendKind_Yes;
  15286. }
  15287. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args, bool force)
  15288. {
  15289. BP_ZONE("BfModule::TryConstCalcAppend");
  15290. BF_ASSERT(methodInst->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  15291. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (!force))
  15292. return BfTypedValue();
  15293. // We want to regenerate all ctor calls when the method internals change
  15294. {
  15295. auto checkTypeInst = methodInst->GetOwner();
  15296. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  15297. {
  15298. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  15299. checkTypeInst = GetBaseType(checkTypeInst);
  15300. }
  15301. }
  15302. if (!methodInst->mMayBeConst)
  15303. return BfTypedValue();
  15304. // Do we need to iterate in order to resolve mAppendAllocAlign?
  15305. bool isFirstRun = methodInst->mEndingAppendAllocAlign < 0;
  15306. bool wasAllConst = true;
  15307. int argIdx = 0;
  15308. int paramIdx = 0;
  15309. while (true)
  15310. {
  15311. if (argIdx >= (int)args.size())
  15312. break;
  15313. auto paramType = methodInst->GetParamType(paramIdx);
  15314. PopulateType(paramType);
  15315. int argCount = 0;
  15316. if (!paramType->IsValuelessType())
  15317. {
  15318. if ((!mIsComptimeModule) && (methodInst->GetParamIsSplat(paramIdx)))
  15319. argCount = paramType->GetSplatCount();
  15320. else
  15321. argCount = 1;
  15322. for (int argOfs = 0; argOfs < argCount; argOfs++)
  15323. {
  15324. auto arg = args[argIdx + argOfs];
  15325. if (!arg.IsConst())
  15326. {
  15327. wasAllConst = false;
  15328. if (!isFirstRun)
  15329. {
  15330. auto& param = methodInst->mParams[argIdx];
  15331. if (param.mReferencedInConstPass)
  15332. {
  15333. // If this param is required as part of the const calculation then
  15334. // we require that it be const...
  15335. return BfTypedValue();
  15336. }
  15337. }
  15338. }
  15339. }
  15340. }
  15341. paramIdx++;
  15342. argIdx += argCount;
  15343. }
  15344. auto methodDef = methodInst->mMethodDef;
  15345. auto methodDecl = methodDef->GetMethodDeclaration();
  15346. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  15347. if (methodDeclBlock == NULL)
  15348. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  15349. BfTypedValue constValue;
  15350. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  15351. auto checkState = mCurMethodState->mConstResolveState;
  15352. while (checkState != NULL)
  15353. {
  15354. if (checkState->mMethodInstance == methodInst)
  15355. {
  15356. return BfTypedValue();
  15357. }
  15358. checkState = checkState->mPrevConstResolveState;
  15359. }
  15360. //auto accumValue = GetConstValue(0);
  15361. bool failed = false;
  15362. //
  15363. {
  15364. BfConstResolveState constResolveState;
  15365. constResolveState.mMethodInstance = methodInst;
  15366. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  15367. constResolveState.mInCalcAppend = true;
  15368. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15369. BfMethodState methodState;
  15370. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  15371. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  15372. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15373. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  15374. methodState.mConstResolveState = &constResolveState;
  15375. int argIdx = 0;
  15376. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  15377. {
  15378. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  15379. continue;
  15380. auto paramType = methodInst->GetParamType(paramIdx);
  15381. // Fix this after we allow structs to be consts
  15382. //BF_ASSERT(!paramType->IsSplattable());
  15383. BfLocalVariable* localVar = new BfLocalVariable();
  15384. localVar->mName = methodInst->GetParamName(paramIdx);
  15385. localVar->mResolvedType = paramType;
  15386. localVar->mConstValue = args[argIdx];
  15387. localVar->mParamIdx = paramIdx;
  15388. AddLocalVariableDef(localVar);
  15389. argIdx++;
  15390. }
  15391. AppendAllocVisitor appendAllocVisitor;
  15392. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  15393. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  15394. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  15395. if (baseCtorAppendValue)
  15396. {
  15397. if (baseCtorAppendValue.mValue.IsFake())
  15398. appendAllocVisitor.mFailed = true;
  15399. else
  15400. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  15401. }
  15402. appendAllocVisitor.mModule = this;
  15403. appendAllocVisitor.VisitChild(methodDecl->mBody);
  15404. if (constResolveState.mFailed)
  15405. appendAllocVisitor.mFailed = true;
  15406. if (!appendAllocVisitor.mFailed)
  15407. constValue = appendAllocVisitor.mConstAccum;
  15408. if (appendAllocVisitor.mHasAppendWantMark)
  15409. methodInst->mHasAppendWantMark = true;
  15410. if (isFirstRun)
  15411. {
  15412. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  15413. if (mCurMethodInstance->mAppendAllocAlign <= 0)
  15414. mCurMethodInstance->mAppendAllocAlign = 1;
  15415. }
  15416. if (isFirstRun)
  15417. {
  15418. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  15419. {
  15420. auto localVar = mCurMethodState->mLocals[paramIdx];
  15421. if (localVar->mReadFromId != -1)
  15422. {
  15423. auto& param = methodInst->mParams[paramIdx];
  15424. param.mReferencedInConstPass = true;
  15425. }
  15426. }
  15427. }
  15428. }
  15429. mBfIRBuilder->SetInsertPoint(prevBlock);
  15430. if (!constValue)
  15431. {
  15432. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  15433. // all-const args
  15434. if (wasAllConst)
  15435. {
  15436. methodInst->mMayBeConst = false;
  15437. }
  15438. }
  15439. return constValue;
  15440. }
  15441. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  15442. {
  15443. // Any errors should only be shown in the actual CTOR call
  15444. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  15445. auto methodDef = mCurMethodInstance->mMethodDef;
  15446. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  15447. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  15448. BfAllowAppendKind allowAppendKind = GetBaseAllowAppend(mCurMethodInstance);
  15449. BfCustomAttributes* customAttributes = NULL;
  15450. defer(delete customAttributes);
  15451. BfInvocationExpression* ctorInvocation = NULL;
  15452. if (ctorDeclaration != NULL)
  15453. {
  15454. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  15455. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  15456. {
  15457. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  15458. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  15459. }
  15460. }
  15461. BfTypeInstance* targetType = NULL;
  15462. if (ctorInvocation != NULL)
  15463. {
  15464. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15465. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15466. }
  15467. else
  15468. targetType = mCurTypeInstance->mBaseType;
  15469. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  15470. return NULL;
  15471. auto targetRefNode = methodDef->GetRefNode();
  15472. BfType* targetThisType = targetType;
  15473. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  15474. BfExprEvaluator exprEvaluator(this);
  15475. BfResolvedArgs argValues;
  15476. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15477. {
  15478. argValues.Init(&ctorInvocation->mArguments);
  15479. }
  15480. //
  15481. {
  15482. }
  15483. BfFunctionBindResult bindResult;
  15484. bindResult.mSkipThis = true;
  15485. bindResult.mWantsArgs = true;
  15486. {
  15487. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15488. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15489. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  15490. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), allowAppendKind, NULL);
  15491. }
  15492. if (bindResult.mMethodInstance == NULL)
  15493. {
  15494. AssertErrorState();
  15495. return BfTypedValue();
  15496. }
  15497. if (!bindResult.mMethodInstance->mMethodDef->HasAppend())
  15498. {
  15499. return BfTypedValue();
  15500. }
  15501. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  15502. bindResult.mIRArgs.RemoveAt(0);
  15503. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  15504. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs, true);
  15505. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  15506. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  15507. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  15508. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  15509. if (appendSizeTypedValue)
  15510. return appendSizeTypedValue;
  15511. if (constOnly)
  15512. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  15513. bool needsRecalc = false;
  15514. for (auto irArg : bindResult.mIRArgs)
  15515. {
  15516. if (irArg.IsFake())
  15517. needsRecalc = true;
  15518. }
  15519. auto calcAppendArgs = bindResult.mIRArgs;
  15520. if (needsRecalc)
  15521. {
  15522. // Do it again, but without mIgnoreWrites set
  15523. BfResolvedArgs argValues;
  15524. argValues.Init(&ctorInvocation->mArguments);
  15525. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15526. BfFunctionBindResult bindResult;
  15527. bindResult.mSkipThis = true;
  15528. bindResult.mWantsArgs = true;
  15529. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  15530. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), allowAppendKind, NULL);
  15531. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  15532. bindResult.mIRArgs.RemoveAt(0);
  15533. calcAppendArgs = bindResult.mIRArgs;
  15534. }
  15535. if (mBfIRBuilder->mIgnoreWrites)
  15536. {
  15537. appendSizeTypedValue = GetFakeTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  15538. }
  15539. else
  15540. {
  15541. BF_ASSERT(calcAppendMethodModule.mFunc);
  15542. appendSizeTypedValue = exprEvaluator.CreateCall(NULL, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  15543. }
  15544. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  15545. return appendSizeTypedValue;
  15546. }
  15547. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  15548. void BfModule::EmitCtorCalcAppend()
  15549. {
  15550. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  15551. return;
  15552. auto methodDef = mCurMethodInstance->mMethodDef;
  15553. auto methodDecl = methodDef->GetMethodDeclaration();
  15554. Array<BfAstNode*> deferredNodeList;
  15555. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  15556. if (methodDeclBlock == NULL)
  15557. return;
  15558. AppendAllocVisitor appendAllocVisitor;
  15559. auto baseCalcAppend = CallBaseCtorCalc(false);
  15560. if (baseCalcAppend)
  15561. {
  15562. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  15563. }
  15564. appendAllocVisitor.mModule = this;
  15565. appendAllocVisitor.VisitChild(methodDecl->mBody);
  15566. }
  15567. void BfModule::CreateStaticCtor()
  15568. {
  15569. auto typeDef = mCurTypeInstance->mTypeDef;
  15570. auto methodDef = mCurMethodInstance->mMethodDef;
  15571. BfIRBlock exitBB;
  15572. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15573. {
  15574. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  15575. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  15576. mBfIRBuilder->MapType(boolType),
  15577. false,
  15578. BfIRLinkageType_Internal,
  15579. GetDefaultValue(boolType),
  15580. "didStaticInit");
  15581. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  15582. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15583. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  15584. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  15585. mBfIRBuilder->SetInsertPoint(initBB);
  15586. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  15587. }
  15588. // Do DLL imports
  15589. if (!mDllImportEntries.empty())
  15590. {
  15591. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  15592. PopulateType(internalType);
  15593. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  15594. if (!getSharedProcAddressInstance)
  15595. {
  15596. if (!mCompiler->mPassInstance->HasFailed())
  15597. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  15598. }
  15599. }
  15600. // Fill in initializer values
  15601. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15602. {
  15603. for (auto fieldDef : typeDef->mFields)
  15604. {
  15605. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic))
  15606. {
  15607. // For extensions, only handle these fields in the appropriate extension
  15608. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15609. continue;
  15610. auto initializer = fieldDef->GetInitializer();
  15611. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15612. if (!fieldInst->mFieldIncluded)
  15613. continue;
  15614. if (fieldInst->mResolvedType->IsVar())
  15615. {
  15616. continue;
  15617. }
  15618. if (fieldInst->IsAppendedObject())
  15619. {
  15620. AppendedObjectInit(fieldInst);
  15621. }
  15622. else if (initializer != NULL)
  15623. {
  15624. UpdateSrcPos(initializer);
  15625. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  15626. }
  15627. }
  15628. }
  15629. auto _CheckInitBlock = [&](BfAstNode* node)
  15630. {
  15631. };
  15632. EmitInitBlocks(_CheckInitBlock);
  15633. }
  15634. else
  15635. {
  15636. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15637. {
  15638. if (tempTypeDef->mFullName == typeDef->mFullName)
  15639. {
  15640. for (auto fieldDef : tempTypeDef->mFields)
  15641. {
  15642. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  15643. {
  15644. if (fieldDef->GetInitializer() != NULL)
  15645. {
  15646. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDef->GetInitializer()))
  15647. {
  15648. sourceClassifier->SetElementType(fieldDef->GetInitializer(), BfSourceElementType_Normal);
  15649. sourceClassifier->VisitChildNoRef(fieldDef->GetInitializer());
  15650. }
  15651. BfType* wantType = NULL;
  15652. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  15653. {
  15654. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  15655. }
  15656. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  15657. if (fieldDef->mIsAppend)
  15658. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  15659. CreateValueFromExpression(fieldDef->GetInitializer(), wantType, exprFlags);
  15660. }
  15661. }
  15662. }
  15663. }
  15664. }
  15665. }
  15666. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15667. CallChainedMethods(mCurMethodInstance, false);
  15668. }
  15669. void BfModule::EmitDtorBody()
  15670. {
  15671. if (!mCurMethodState->mIRExitBlock)
  15672. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15673. if (mCurTypeInstance->IsClosure())
  15674. {
  15675. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  15676. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  15677. auto thisVal = GetThis();
  15678. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  15679. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  15680. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  15681. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  15682. SizedArray<BfIRValue, 1> args;
  15683. args.push_back(thisVal.mValue);
  15684. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  15685. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15686. // Fall through to Object::~this call
  15687. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  15688. if (mIsComptimeModule)
  15689. mCompiler->mCeMachine->QueueMethod(dtorFunc.mMethodInstance, dtorFunc.mFunc);
  15690. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  15691. SizedArray<BfIRValue, 1> vals = { basePtr };
  15692. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  15693. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  15694. mBfIRBuilder->SetTailCall(result);
  15695. return;
  15696. }
  15697. auto typeDef = mCurTypeInstance->mTypeDef;
  15698. auto methodDef = mCurMethodInstance->mMethodDef;
  15699. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15700. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15701. CallChainedMethods(mCurMethodInstance, true);
  15702. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15703. {
  15704. VisitEmbeddedStatement(bodyBlock);
  15705. if (bodyBlock->mCloseBrace != NULL)
  15706. {
  15707. UpdateSrcPos(bodyBlock->mCloseBrace);
  15708. }
  15709. }
  15710. else
  15711. {
  15712. if (methodDeclaration != NULL)
  15713. UpdateSrcPos(methodDeclaration);
  15714. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15715. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  15716. else if (typeDef->mTypeDeclaration != NULL)
  15717. UpdateSrcPos(typeDef->mTypeDeclaration);
  15718. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  15719. {
  15720. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  15721. }
  15722. }
  15723. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15724. {
  15725. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  15726. {
  15727. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  15728. auto fieldDef = fieldInst->GetFieldDef();
  15729. BfFieldDeclaration* fieldDecl = NULL;
  15730. if (fieldDef != NULL)
  15731. fieldDecl = fieldDef->GetFieldDeclaration();
  15732. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDecl != NULL) && (fieldDecl->mFieldDtor != NULL))
  15733. {
  15734. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15735. {
  15736. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15737. continue;
  15738. }
  15739. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  15740. {
  15741. Fail("Structs cannot have field destructors", fieldDecl->mFieldDtor->mTildeToken, true);
  15742. }
  15743. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  15744. auto fieldDtor = fieldDecl->mFieldDtor;
  15745. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  15746. continue;
  15747. UpdateSrcPos(fieldDtor);
  15748. BfScopeData scopeData;
  15749. mCurMethodState->AddScope(&scopeData);
  15750. NewScopeState();
  15751. UpdateSrcPos(fieldDtor);
  15752. bool hasDbgInfo = (!fieldDef->mIsConst);
  15753. if (hasDbgInfo)
  15754. {
  15755. mBfIRBuilder->SaveDebugLocation();
  15756. mBfIRBuilder->ClearDebugLocation();
  15757. }
  15758. BfIRValue value;
  15759. if (fieldDef->mIsStatic)
  15760. {
  15761. value = ReferenceStaticField(fieldInst).mValue;
  15762. }
  15763. else
  15764. {
  15765. PopulateType(fieldInst->mResolvedType);
  15766. if (fieldInst->mResolvedType->IsValuelessType())
  15767. {
  15768. value = mBfIRBuilder->GetFakeVal();
  15769. }
  15770. else if (!mCurTypeInstance->IsValueType())
  15771. {
  15772. auto thisValue = GetThis();
  15773. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  15774. }
  15775. else
  15776. {
  15777. AssertErrorState();
  15778. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15779. }
  15780. }
  15781. BfIRValue staticVal;
  15782. if (hasDbgInfo)
  15783. {
  15784. BfIRValue dbgShowValue = value;
  15785. BfLocalVariable* localDef = new BfLocalVariable();
  15786. localDef->mName = "_";
  15787. localDef->mResolvedType = fieldInst->mResolvedType;
  15788. if ((fieldInst->IsAppendedObject()) && (!fieldDef->mIsStatic))
  15789. {
  15790. localDef->mValue = mBfIRBuilder->CreateBitCast(value, mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15791. }
  15792. else
  15793. {
  15794. localDef->mAddr = value;
  15795. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  15796. {
  15797. // Create another pointer indirection, a ref to the gep
  15798. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  15799. auto allocaInst = CreateAlloca(refFieldType);
  15800. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  15801. localDef->mResolvedType = refFieldType;
  15802. localDef->mAddr = allocaInst;
  15803. }
  15804. }
  15805. mBfIRBuilder->RestoreDebugLocation();
  15806. auto defLocalVar = AddLocalVariableDef(localDef, true);
  15807. if ((!fieldInst->IsAppendedObject()) && (!fieldDef->mIsStatic))
  15808. {
  15809. // Put back so we actually modify the correct value*/
  15810. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  15811. defLocalVar->mAddr = value;
  15812. }
  15813. }
  15814. while (fieldDtor != NULL)
  15815. {
  15816. if (mCompiler->mResolvePassData != NULL)
  15817. {
  15818. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15819. {
  15820. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15821. sourceClassifier->VisitChild(fieldDtor);
  15822. }
  15823. }
  15824. UpdateSrcPos(fieldDtor);
  15825. VisitEmbeddedStatement(fieldDtor->mBody);
  15826. fieldDtor = fieldDtor->mNextFieldDtor;
  15827. }
  15828. RestoreScopeState();
  15829. }
  15830. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldInst->IsAppendedObject()))
  15831. {
  15832. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15833. {
  15834. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15835. continue;
  15836. }
  15837. auto refNode = fieldDef->GetRefNode();
  15838. UpdateSrcPos(refNode);
  15839. auto objectType = mContext->mBfObjectType;
  15840. BfTypeInstance* checkTypeInst = mCurTypeInstance->ToTypeInstance();
  15841. BfTypedValue val;
  15842. if (fieldDef->mIsStatic)
  15843. {
  15844. val = ReferenceStaticField(fieldInst);
  15845. val = LoadValue(val);
  15846. }
  15847. else
  15848. {
  15849. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  15850. val = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  15851. }
  15852. bool allowPrivate = checkTypeInst == mCurTypeInstance;
  15853. bool allowProtected = allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst);
  15854. while (checkTypeInst != NULL)
  15855. {
  15856. auto dtorMethodDef = checkTypeInst->mTypeDef->GetMethodByName("~this");
  15857. if (dtorMethodDef)
  15858. {
  15859. if (!CheckProtection(dtorMethodDef->mProtection, checkTypeInst->mTypeDef, allowProtected, allowPrivate))
  15860. {
  15861. auto error = Fail(StrFormat("'%s.~this()' is inaccessible due to its protection level", TypeToString(checkTypeInst).c_str()), refNode); // CS0122
  15862. }
  15863. }
  15864. checkTypeInst = checkTypeInst->mBaseType;
  15865. allowPrivate = false;
  15866. }
  15867. // call dtor
  15868. BfExprEvaluator expressionEvaluator(this);
  15869. PopulateType(val.mType);
  15870. PopulateType(objectType, BfPopulateType_DataAndMethods);
  15871. EmitObjectAccessCheck(val);
  15872. if (objectType->mVirtualMethodTable.size() == 0)
  15873. {
  15874. if (!mCompiler->IsAutocomplete())
  15875. AssertErrorState();
  15876. }
  15877. else if (!IsSkippingExtraResolveChecks())
  15878. {
  15879. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  15880. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  15881. SizedArray<BfIRValue, 4> llvmArgs;
  15882. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  15883. expressionEvaluator.CreateCall(refNode, methodInstance, mBfIRBuilder->GetFakeVal(), false, llvmArgs);
  15884. }
  15885. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  15886. {
  15887. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  15888. auto int8PtrVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(int8PtrType));
  15889. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  15890. }
  15891. }
  15892. }
  15893. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15894. {
  15895. auto checkBaseType = mCurTypeInstance->mBaseType;
  15896. while (checkBaseType != NULL)
  15897. {
  15898. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15899. {
  15900. if (bodyBlock->mCloseBrace != NULL)
  15901. UpdateSrcPos(bodyBlock->mCloseBrace);
  15902. }
  15903. else
  15904. {
  15905. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  15906. }
  15907. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  15908. if (dtorMethodDef != NULL)
  15909. {
  15910. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  15911. if (IsSkippingExtraResolveChecks())
  15912. {
  15913. // Nothing
  15914. }
  15915. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  15916. {
  15917. if ((!IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  15918. {
  15919. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  15920. SizedArray<BfIRValue, 1> vals = { basePtr };
  15921. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  15922. if (mIsComptimeModule)
  15923. mCompiler->mCeMachine->QueueMethod(dtorMethodInstance.mMethodInstance, dtorMethodInstance.mFunc);
  15924. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  15925. }
  15926. }
  15927. else
  15928. {
  15929. // Invalid base dtor declaration
  15930. AssertErrorState();
  15931. }
  15932. break;
  15933. }
  15934. checkBaseType = checkBaseType->mBaseType;
  15935. }
  15936. }
  15937. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15938. }
  15939. else
  15940. {
  15941. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15942. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15943. // resolve pass, NOT the autocomplete expression
  15944. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15945. {
  15946. if (tempTypeDef->mFullName == typeDef->mFullName)
  15947. {
  15948. for (auto fieldDef : tempTypeDef->mFields)
  15949. {
  15950. auto fieldDecl = fieldDef->GetFieldDeclaration();
  15951. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  15952. (fieldDecl->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  15953. {
  15954. BfType* fieldType = NULL;
  15955. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  15956. {
  15957. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  15958. auto curFieldDef = curFieldInstance->GetFieldDef();
  15959. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  15960. fieldType = curFieldInstance->GetResolvedType();
  15961. }
  15962. if (fieldType == NULL)
  15963. fieldType = GetPrimitiveType(BfTypeCode_Var);
  15964. auto fieldDtor = fieldDecl->mFieldDtor;
  15965. BfScopeData scopeData;
  15966. mCurMethodState->AddScope(&scopeData);
  15967. NewScopeState();
  15968. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  15969. if (fieldType != NULL)
  15970. {
  15971. BfLocalVariable* localDef = new BfLocalVariable();
  15972. localDef->mName = "_";
  15973. localDef->mResolvedType = fieldType;
  15974. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  15975. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15976. AddLocalVariableDef(localDef);
  15977. }
  15978. while (fieldDtor != NULL)
  15979. {
  15980. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15981. {
  15982. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15983. sourceClassifier->VisitChild(fieldDtor);
  15984. }
  15985. UpdateSrcPos(fieldDtor);
  15986. VisitEmbeddedStatement(fieldDtor->mBody);
  15987. fieldDtor = fieldDtor->mNextFieldDtor;
  15988. }
  15989. RestoreScopeState();
  15990. }
  15991. }
  15992. }
  15993. }
  15994. }
  15995. // If there are appends then we just need the rootmost append type to do the Dbg_AppendDeleted
  15996. if ((!mIsComptimeModule) && (!methodDef->mIsStatic) && (mCompiler->mOptions.mDebugAlloc) &&
  15997. (mCurTypeInstance->HasAppendCtor()) && (!mCurTypeInstance->BaseHasAppendCtor()))
  15998. {
  15999. auto thisValue = GetThis();
  16000. auto appendedObj = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  16001. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_AppendDeleted", 2);
  16002. SizedArray<BfIRValue, 1> llvmArgs;
  16003. llvmArgs.Add(appendedObj);
  16004. llvmArgs.Add(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mCurMethodState->mDisableChecks ? 0 : 1));
  16005. if (allocMethod)
  16006. mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  16007. }
  16008. }
  16009. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  16010. {
  16011. BF_ASSERT(methodInstance->mIsReified);
  16012. auto typeInstance = methodInstance->GetOwner();
  16013. bool foundDllImportAttr = false;
  16014. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  16015. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  16016. {
  16017. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  16018. {
  16019. foundDllImportAttr = true;
  16020. }
  16021. }
  16022. if (!foundDllImportAttr)
  16023. {
  16024. AssertErrorState();
  16025. return BfIRValue();
  16026. }
  16027. StringT<512> name = "bf_hs_preserve@";
  16028. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  16029. name += "__imp";
  16030. BfIRType returnType;
  16031. SizedArray<BfIRType, 8> paramTypes;
  16032. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  16033. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  16034. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  16035. BfIRValue initVal;
  16036. if (define)
  16037. {
  16038. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  16039. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  16040. }
  16041. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  16042. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  16043. {
  16044. auto voidType = GetPrimitiveType(BfTypeCode_None);
  16045. auto ptrType = CreatePointerType(voidType);
  16046. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  16047. }
  16048. return globalVar;
  16049. }
  16050. void BfModule::CreateDllImportMethod()
  16051. {
  16052. if (mBfIRBuilder->mIgnoreWrites)
  16053. return;
  16054. auto globalVar = mFuncReferences[mCurMethodInstance];
  16055. if (!globalVar)
  16056. return;
  16057. bool allowTailCall = true;
  16058. mBfIRBuilder->ClearDebugLocation();
  16059. bool isHotCompile = mCompiler->IsHotCompile();
  16060. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  16061. if (isHotCompile)
  16062. {
  16063. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  16064. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  16065. }
  16066. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  16067. BfIRType returnType;
  16068. SizedArray<BfIRType, 8> paramTypes;
  16069. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  16070. SizedArray<BfIRValue, 8> args;
  16071. for (int i = 0; i < (int)paramTypes.size(); i++)
  16072. args.push_back(mBfIRBuilder->GetArgument(i));
  16073. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  16074. if (isHotCompile)
  16075. {
  16076. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  16077. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  16078. if (callingConvention == BfIRCallingConv_StdCall)
  16079. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  16080. else if (callingConvention == BfIRCallingConv_FastCall)
  16081. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  16082. else
  16083. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  16084. if (allowTailCall)
  16085. mBfIRBuilder->SetTailCall(result);
  16086. CreateReturn(result);
  16087. mCurMethodState->mHadReturn = true;
  16088. }
  16089. if (HasCompiledOutput())
  16090. {
  16091. BfDllImportEntry dllImportEntry;
  16092. dllImportEntry.mFuncVar = globalVar;
  16093. dllImportEntry.mMethodInstance = mCurMethodInstance;
  16094. mDllImportEntries.push_back(dllImportEntry);
  16095. }
  16096. }
  16097. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  16098. {
  16099. auto methodDef = methodInstance->mMethodDef;
  16100. BfTypeInstance* owner = NULL;
  16101. if (!methodDef->mIsStatic)
  16102. owner = methodInstance->GetThisType()->ToTypeInstance();
  16103. if (owner == NULL)
  16104. owner = methodInstance->GetOwner();
  16105. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  16106. return BfIRCallingConv_CDecl;
  16107. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  16108. return BfIRCallingConv_StdCall;
  16109. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  16110. return BfIRCallingConv_FastCall;
  16111. if (!methodDef->mIsStatic)
  16112. {
  16113. if (owner->mIsCRepr)
  16114. return BfIRCallingConv_ThisCall;
  16115. if ((!owner->IsValuelessType()) &&
  16116. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  16117. return BfIRCallingConv_ThisCall;
  16118. }
  16119. return BfIRCallingConv_CDecl;
  16120. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  16121. }
  16122. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  16123. {
  16124. BfMethodDef* methodDef = NULL;
  16125. if (methodInstance != NULL)
  16126. methodDef = methodInstance->mMethodDef;
  16127. if (!func)
  16128. return;
  16129. if (mCompiler->mOptions.mNoFramePointerElim)
  16130. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  16131. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  16132. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  16133. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  16134. if (methodInstance == NULL)
  16135. return;
  16136. if (methodInstance->mReturnType->IsVar())
  16137. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_VarRet);
  16138. if (methodDef->mImportKind == BfImportKind_Export)
  16139. {
  16140. if (methodDef->mDeclaringType->mProject->mTargetType != BfTargetType_BeefLib_StaticLib)
  16141. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  16142. }
  16143. if (methodDef->mIsNoReturn)
  16144. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  16145. auto callingConv = GetIRCallingConvention(methodInstance);
  16146. if (callingConv != BfIRCallingConv_CDecl)
  16147. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  16148. if (isInlined)
  16149. {
  16150. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  16151. }
  16152. int argIdx = 0;
  16153. int paramIdx = 0;
  16154. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  16155. paramIdx = -1;
  16156. int argCount = methodInstance->GetIRFunctionParamCount(this);
  16157. while (argIdx < argCount)
  16158. {
  16159. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16160. {
  16161. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  16162. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  16163. argIdx++;
  16164. continue;
  16165. }
  16166. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  16167. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  16168. paramIdx++;
  16169. BfType* resolvedTypeRef = NULL;
  16170. BfType* resolvedTypeRef2 = NULL;
  16171. String paramName;
  16172. bool isSplattable = false;
  16173. bool tryLowering = !mIsComptimeModule;
  16174. if (isThis)
  16175. {
  16176. paramName = "this";
  16177. if (methodInstance->mIsClosure)
  16178. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  16179. else
  16180. resolvedTypeRef = methodInstance->GetThisType();
  16181. isSplattable = (!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(-1));
  16182. tryLowering = (!mIsComptimeModule) && (methodInstance->AllowsSplatting(-1));
  16183. }
  16184. else
  16185. {
  16186. paramName = methodInstance->GetParamName(paramIdx);
  16187. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  16188. if (resolvedTypeRef->IsMethodRef())
  16189. isSplattable = true;
  16190. else if ((!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(paramIdx)))
  16191. {
  16192. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  16193. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  16194. {
  16195. // crepr splat is always splattable
  16196. isSplattable = true;
  16197. }
  16198. else
  16199. {
  16200. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  16201. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  16202. isSplattable = true;
  16203. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  16204. isSplattable = true;
  16205. }
  16206. }
  16207. }
  16208. if (tryLowering)
  16209. {
  16210. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16211. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16212. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  16213. {
  16214. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  16215. argIdx++;
  16216. if (loweredTypeCode2 != BfTypeCode_None)
  16217. {
  16218. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  16219. argIdx++;
  16220. }
  16221. paramIdx++;
  16222. continue;
  16223. }
  16224. }
  16225. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  16226. {
  16227. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  16228. int addDeref = -1;
  16229. if (resolvedTypeRef->IsRef())
  16230. {
  16231. auto refType = (BfRefType*)resolvedTypeRef;
  16232. auto elementType = refType->mElementType;
  16233. PopulateType(elementType, BfPopulateType_Data);
  16234. addDeref = elementType->mSize;
  16235. if ((addDeref <= 0) && (!elementType->IsValuelessType()) && (!elementType->IsOpaque()))
  16236. AssertErrorState();
  16237. }
  16238. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  16239. {
  16240. if (isThis)
  16241. {
  16242. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  16243. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  16244. addDeref = resolvedTypeRef->mSize;
  16245. }
  16246. else if (methodInstance->WantsStructsAttribByVal(resolvedTypeRef))
  16247. {
  16248. mBfIRBuilder->PopulateType(resolvedTypeRef, BfIRPopulateType_Full);
  16249. BF_ASSERT(resolvedTypeRef->mAlign > 0);
  16250. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  16251. }
  16252. }
  16253. else if (resolvedTypeRef->IsPrimitiveType())
  16254. {
  16255. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  16256. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  16257. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  16258. }
  16259. if (addDeref >= 0)
  16260. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  16261. argIdx++;
  16262. };
  16263. if (isSplattable)
  16264. {
  16265. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  16266. {
  16267. if (checkType->IsStruct())
  16268. {
  16269. auto checkTypeInstance = checkType->ToTypeInstance();
  16270. if (checkTypeInstance->mBaseType != NULL)
  16271. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  16272. if (checkTypeInstance->mIsUnion)
  16273. {
  16274. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  16275. checkTypeLambda(unionInnerType, curName + "_data");
  16276. }
  16277. else
  16278. {
  16279. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  16280. {
  16281. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  16282. auto fieldDef = fieldInstance->GetFieldDef();
  16283. if (fieldInstance->mDataIdx >= 0)
  16284. {
  16285. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  16286. }
  16287. }
  16288. }
  16289. if (checkTypeInstance->IsEnum())
  16290. {
  16291. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  16292. argIdx++;
  16293. }
  16294. }
  16295. else if (checkType->IsMethodRef())
  16296. {
  16297. auto methodRefType = (BfMethodRefType*)checkType;
  16298. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  16299. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  16300. {
  16301. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  16302. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  16303. {
  16304. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  16305. }
  16306. else
  16307. {
  16308. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  16309. }
  16310. }
  16311. }
  16312. else if (!checkType->IsValuelessType())
  16313. {
  16314. _SetupParam(curName, checkType);
  16315. }
  16316. };
  16317. checkTypeLambda(resolvedTypeRef, paramName);
  16318. paramIdx++;
  16319. continue;
  16320. }
  16321. _SetupParam(paramName, resolvedTypeRef);
  16322. if (resolvedTypeRef2 != NULL)
  16323. _SetupParam(paramName, resolvedTypeRef2);
  16324. paramIdx++;
  16325. }
  16326. }
  16327. void BfModule::EmitInitBlocks(const std::function<void(BfAstNode*)>& initBlockCallback)
  16328. {
  16329. auto methodDef = mCurMethodInstance->mMethodDef;
  16330. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  16331. BfMemberSetEntry* entry = NULL;
  16332. BfMethodDef* initMethodDef = NULL;
  16333. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  16334. if (entry != NULL)
  16335. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  16336. SizedArray<BfAstNode*, 8> initBodies;
  16337. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  16338. {
  16339. if (initMethodDef->mDeclaringType->GetDefinition() != methodDef->mDeclaringType->GetDefinition())
  16340. continue;
  16341. if (initMethodDef->mMethodType != BfMethodType_Init)
  16342. continue;
  16343. if (initMethodDef->mIsStatic != methodDef->mIsStatic)
  16344. continue;
  16345. initBodies.Insert(0, initMethodDef->mBody);
  16346. }
  16347. for (auto body : initBodies)
  16348. {
  16349. initBlockCallback(body);
  16350. VisitEmbeddedStatement(body);
  16351. }
  16352. }
  16353. void BfModule::EmitCtorBody(bool& skipBody)
  16354. {
  16355. auto methodInstance = mCurMethodInstance;
  16356. auto methodDef = methodInstance->mMethodDef;
  16357. auto methodDeclaration = methodDef->mMethodDeclaration;
  16358. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  16359. auto typeDef = mCurTypeInstance->mTypeDef;
  16360. BfCustomAttributes* customAttributes = NULL;
  16361. defer(delete customAttributes);
  16362. BfInvocationExpression* ctorInvocation = NULL;
  16363. BfAttributeState attributeState;
  16364. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  16365. if (ctorDeclaration != NULL)
  16366. {
  16367. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  16368. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  16369. {
  16370. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  16371. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  16372. }
  16373. }
  16374. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  16375. // Prologue
  16376. mBfIRBuilder->ClearDebugLocation();
  16377. bool hadThisInitializer = false;
  16378. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16379. {
  16380. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  16381. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  16382. if (targetToken->GetToken() == BfToken_This)
  16383. {
  16384. hadThisInitializer = true;
  16385. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  16386. mCurMethodState->LocalDefined(GetThisVariable());
  16387. }
  16388. }
  16389. // Zero out memory for default ctor
  16390. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()) && (!mCurTypeInstance->IsAnonymousInitializerType()) && (methodInstance->mChainType != BfMethodChainType_ChainMember) &&
  16391. (!mCurMethodState->mLocals.IsEmpty()))
  16392. {
  16393. if (mCurTypeInstance->IsTypedPrimitive())
  16394. {
  16395. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  16396. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  16397. }
  16398. else if (mCurTypeInstance->mInstSize > 0)
  16399. {
  16400. BfIRValue fillValue = GetConstValue8(0);
  16401. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  16402. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  16403. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  16404. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  16405. }
  16406. }
  16407. BfAstNode* baseCtorNode = NULL;
  16408. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  16409. baseCtorNode = ctorInvocation->mTarget;
  16410. else if (methodDef->mBody != NULL)
  16411. baseCtorNode = methodDef->mBody;
  16412. else if (ctorDeclaration != NULL)
  16413. baseCtorNode = ctorDeclaration;
  16414. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  16415. baseCtorNode = methodDef->mDeclaringType->GetRefNode();
  16416. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  16417. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  16418. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  16419. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  16420. else
  16421. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  16422. bool calledCtorNoBody = false;
  16423. if ((mCurTypeInstance->IsTypedPrimitive()) && (!mCurTypeInstance->IsValuelessType()))
  16424. {
  16425. // Zero out typed primitives in ctor
  16426. mBfIRBuilder->CreateAlignedStore(GetDefaultValue(mCurTypeInstance->GetUnderlyingType()), mBfIRBuilder->GetArgument(0), mCurTypeInstance->mAlign);
  16427. }
  16428. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  16429. {
  16430. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  16431. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  16432. {
  16433. BfMethodDef* defaultCtor = NULL;
  16434. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  16435. {
  16436. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  16437. {
  16438. defaultCtor = methodDef;
  16439. }
  16440. }
  16441. if (defaultCtor != NULL)
  16442. {
  16443. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  16444. SetIllegalSrcPos();
  16445. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  16446. BfExprEvaluator exprEvaluator(this);
  16447. SizedArray<BfIRValue, 1> irArgs;
  16448. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  16449. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  16450. if (mIsComptimeModule)
  16451. mCompiler->mCeMachine->QueueMethod(moduleMethodInstance);
  16452. calledCtorNoBody = true;
  16453. }
  16454. }
  16455. }
  16456. // Initialize fields (if applicable)
  16457. if (mCurTypeInstance->IsBoxed())
  16458. {
  16459. skipBody = true;
  16460. }
  16461. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  16462. {
  16463. // Field initializers occur in CtorNoBody methods for extensions
  16464. }
  16465. else if (!hadThisInitializer)
  16466. {
  16467. // If we had a 'this' initializer, that other ctor will have initialized our fields
  16468. //auto
  16469. if ((!mCompiler->mIsResolveOnly) ||
  16470. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  16471. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  16472. {
  16473. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  16474. // to properly set the assigned flags
  16475. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  16476. bool hadInlineInitBlock = false;
  16477. BfScopeData scopeData;
  16478. scopeData.mInInitBlock = true;
  16479. auto _CheckInitBlock = [&](BfAstNode* node)
  16480. {
  16481. if (!hadInlineInitBlock)
  16482. {
  16483. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  16484. {
  16485. UpdateSrcPos(baseCtorNode);
  16486. if (methodDef->mBody == NULL)
  16487. SetIllegalSrcPos();
  16488. // 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
  16489. EmitEnsureInstructionAt();
  16490. BfType* thisType = mCurTypeInstance;
  16491. if (thisType->IsValueType())
  16492. thisType = CreateRefType(thisType);
  16493. SizedArray<BfIRMDNode, 1> diParamTypes;
  16494. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  16495. mCurMethodState->AddScope(&scopeData);
  16496. NewScopeState();
  16497. int flags = 0;
  16498. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  16499. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  16500. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  16501. String linkageName;
  16502. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mCurBuilder != NULL))
  16503. linkageName = StrFormat("%d", mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(mCurMethodInstance, "$initFields"));
  16504. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", linkageName, mCurFilePosition.mFileInstance->mDIFile,
  16505. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  16506. UpdateSrcPos(node);
  16507. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  16508. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  16509. if (!mCurTypeInstance->IsValuelessType())
  16510. {
  16511. auto loadedThis = GetThis();
  16512. // LLVM can't handle two variables pointing to the same value
  16513. BfIRValue copiedThisPtr;
  16514. copiedThisPtr = CreateAlloca(thisType);
  16515. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  16516. mBfIRBuilder->ClearDebugLocation(storeInst);
  16517. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  16518. }
  16519. hadInlineInitBlock = true;
  16520. }
  16521. else
  16522. {
  16523. // Just do a simple one
  16524. mCurMethodState->AddScope(&scopeData);
  16525. NewScopeState();
  16526. hadInlineInitBlock = true;
  16527. }
  16528. }
  16529. UpdateSrcPos(node);
  16530. };
  16531. for (auto fieldDef : typeDef->mFields)
  16532. {
  16533. // For extensions, only handle these fields in the appropriate extension
  16534. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16535. continue;
  16536. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  16537. {
  16538. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  16539. if (!fieldInst->mFieldIncluded)
  16540. continue;
  16541. if (fieldInst->mDataIdx < 0)
  16542. continue;
  16543. auto initializer = fieldDef->GetInitializer();
  16544. if (fieldInst->IsAppendedObject())
  16545. {
  16546. UpdateSrcPos(fieldDef->GetNameNode());
  16547. AppendedObjectInit(fieldInst);
  16548. continue;
  16549. }
  16550. if (initializer == NULL)
  16551. {
  16552. continue;
  16553. // if (fieldDef->mProtection != BfProtection_Hidden)
  16554. // continue;
  16555. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  16556. // continue;
  16557. }
  16558. if (fieldInst->mResolvedType == NULL)
  16559. {
  16560. BF_ASSERT(mHadBuildError);
  16561. continue;
  16562. }
  16563. if (initializer != NULL)
  16564. {
  16565. _CheckInitBlock(initializer);
  16566. }
  16567. BfIRValue fieldAddr;
  16568. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  16569. {
  16570. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  16571. }
  16572. else
  16573. {
  16574. // Failed
  16575. }
  16576. auto assignValue = GetFieldInitializerValue(fieldInst);
  16577. if (mCurTypeInstance->IsUnion())
  16578. {
  16579. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  16580. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  16581. }
  16582. if ((fieldAddr) && (assignValue))
  16583. mBfIRBuilder->CreateAlignedStore(assignValue.mValue, fieldAddr, fieldInst->mResolvedType->mAlign);
  16584. }
  16585. }
  16586. EmitInitBlocks(_CheckInitBlock);
  16587. if (hadInlineInitBlock)
  16588. {
  16589. RestoreScopeState();
  16590. // This gets set to false because of AddScope but we actually are still in the head block
  16591. mCurMethodState->mInHeadScope = true;
  16592. // Make sure we emit a return even if we had a NoReturn call or return inside ourselves
  16593. mCurMethodState->mHadReturn = false;
  16594. mCurMethodState->mLeftBlockUncond = false;
  16595. }
  16596. }
  16597. else // Autocomplete case
  16598. {
  16599. BfScopeData scopeData;
  16600. scopeData.mInInitBlock = true;
  16601. mCurMethodState->AddScope(&scopeData);
  16602. NewScopeState();
  16603. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  16604. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  16605. // resolve pass, NOT the autocomplete expression
  16606. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  16607. {
  16608. if (tempTypeDef->mFullName == typeDef->mFullName)
  16609. {
  16610. for (auto fieldDef : tempTypeDef->mFields)
  16611. {
  16612. auto initializer = fieldDef->GetInitializer();
  16613. if ((!fieldDef->mIsStatic) && (initializer != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  16614. {
  16615. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  16616. {
  16617. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  16618. sourceClassifier->VisitChild(initializer);
  16619. }
  16620. BfType* wantType = NULL;
  16621. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) &&
  16622. (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  16623. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowInferredSizedArray);
  16624. if ((wantType != NULL) &&
  16625. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  16626. wantType = NULL;
  16627. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  16628. if (fieldDef->mIsAppend)
  16629. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  16630. CreateValueFromExpression(initializer, wantType, exprFlags);
  16631. }
  16632. }
  16633. tempTypeDef->PopulateMemberSets();
  16634. BfMemberSetEntry* entry = NULL;
  16635. BfMethodDef* initMethodDef = NULL;
  16636. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  16637. if (entry != NULL)
  16638. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  16639. SizedArray<BfAstNode*, 8> initBodies;
  16640. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  16641. {
  16642. if (initMethodDef->mMethodType != BfMethodType_Init)
  16643. continue;
  16644. initBodies.Insert(0, initMethodDef->mBody);
  16645. }
  16646. for (auto body : initBodies)
  16647. VisitEmbeddedStatement(body);
  16648. }
  16649. }
  16650. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  16651. for (auto fieldDef : typeDef->mFields)
  16652. {
  16653. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->GetInitializer() != NULL))
  16654. {
  16655. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  16656. if (fieldDef->GetInitializer() != NULL)
  16657. MarkFieldInitialized(fieldInst);
  16658. }
  16659. }
  16660. RestoreScopeState();
  16661. }
  16662. }
  16663. if (!methodInstance->mIsAutocompleteMethod)
  16664. {
  16665. if (auto autoDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  16666. {
  16667. BfExprEvaluator exprEvaluator(this);
  16668. for (int paramIdx = 0; paramIdx < methodDef->mParams.mSize; paramIdx++)
  16669. {
  16670. auto paramDef = methodDef->mParams[paramIdx];
  16671. auto& fieldInstance = mCurTypeInstance->mFieldInstances[paramIdx];
  16672. BF_ASSERT(paramDef->mName == fieldInstance.GetFieldDef()->mName);
  16673. if (fieldInstance.mDataIdx < 0)
  16674. continue;
  16675. if (paramDef->mParamKind != BfParamKind_Normal)
  16676. continue;
  16677. auto localVar = mCurMethodState->mLocals[paramIdx + 1];
  16678. BF_ASSERT(localVar->mName == paramDef->mName);
  16679. auto localVal = exprEvaluator.LoadLocal(localVar);
  16680. localVal = LoadOrAggregateValue(localVal);
  16681. if (!localVal.mType->IsVar())
  16682. {
  16683. auto thisVal = GetThis();
  16684. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance.mDataIdx);
  16685. if (mCurTypeInstance->IsUnion())
  16686. fieldPtr = mBfIRBuilder->CreateBitCast(fieldPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInstance.mResolvedType)));
  16687. mBfIRBuilder->CreateAlignedStore(localVal.mValue, fieldPtr, localVar->mResolvedType->mAlign);
  16688. }
  16689. MarkFieldInitialized(&fieldInstance);
  16690. }
  16691. }
  16692. }
  16693. // Call base ctor (if applicable)
  16694. BfTypeInstance* targetType = NULL;
  16695. BfAstNode* targetRefNode = NULL;
  16696. if (ctorDeclaration != NULL)
  16697. targetRefNode = ctorDeclaration->mInitializer;
  16698. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  16699. targetRefNode = invocationExpr->mTarget;
  16700. if (targetRefNode == NULL)
  16701. targetRefNode = mCurTypeInstance->mTypeDef->GetRefNode();
  16702. if (baseCtorNode != NULL)
  16703. {
  16704. UpdateSrcPos(baseCtorNode);
  16705. if (methodDef->mBody == NULL)
  16706. SetIllegalSrcPos();
  16707. }
  16708. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16709. {
  16710. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  16711. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  16712. }
  16713. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()) && (methodDef->mMethodType != BfMethodType_CtorNoBody))
  16714. {
  16715. auto baseType = mCurTypeInstance->mBaseType;
  16716. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  16717. ((baseType->mTypeDef != mCompiler->mValueTypeTypeDef) || (!mContext->mCanSkipValueTypeCtor)) &&
  16718. ((baseType->mTypeDef != mCompiler->mBfObjectTypeDef) || (!mContext->mCanSkipObjectCtor)))
  16719. {
  16720. // Try to find a ctor without any params first
  16721. BfMethodDef* matchedMethod = NULL;
  16722. bool hadCtorWithAllDefaults = false;
  16723. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  16724. for (int pass = 0; pass < 2; pass++)
  16725. {
  16726. baseType->mTypeDef->PopulateMemberSets();
  16727. BfMemberSetEntry* entry = NULL;
  16728. BfMethodDef* checkMethodDef = NULL;
  16729. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  16730. if (entry != NULL)
  16731. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  16732. while (checkMethodDef != NULL)
  16733. {
  16734. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  16735. if (isHiddenGenerated)
  16736. {
  16737. // Allow calling of the default base ctor if it is implicitly defined
  16738. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  16739. allowMethod = true;
  16740. }
  16741. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  16742. {
  16743. if (checkMethodDef->mParams.size() == 0)
  16744. {
  16745. if (matchedMethod != NULL)
  16746. {
  16747. // Has multiple matched methods - can happen from extensions
  16748. matchedMethod = NULL;
  16749. break;
  16750. }
  16751. matchedMethod = checkMethodDef;
  16752. }
  16753. else if (isHiddenGenerated)
  16754. {
  16755. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  16756. hadCtorWithAllDefaults = true;
  16757. }
  16758. }
  16759. checkMethodDef = checkMethodDef->mNextWithSameName;
  16760. }
  16761. if (matchedMethod != NULL)
  16762. break;
  16763. }
  16764. if ((HasExecutedOutput()) && (matchedMethod != NULL))
  16765. {
  16766. SizedArray<BfIRValue, 1> args;
  16767. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  16768. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  16769. {
  16770. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  16771. args.push_back(basePtr);
  16772. }
  16773. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  16774. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  16775. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  16776. if (callingConv != BfIRCallingConv_CDecl)
  16777. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  16778. if (mIsComptimeModule)
  16779. mCompiler->mCeMachine->QueueMethod(ctorBodyMethodInstance);
  16780. }
  16781. if (matchedMethod == NULL)
  16782. {
  16783. targetType = mCurTypeInstance->mBaseType;
  16784. if (ctorDeclaration != NULL)
  16785. targetRefNode = ctorDeclaration->mThisToken;
  16786. else if ((typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mNameNode != NULL))
  16787. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  16788. }
  16789. }
  16790. }
  16791. if (methodDef->HasAppend())
  16792. {
  16793. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  16794. }
  16795. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  16796. {
  16797. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  16798. {
  16799. if (targetType == mCurTypeInstance)
  16800. {
  16801. auto thisVariable = GetThisVariable();
  16802. if (thisVariable != NULL)
  16803. {
  16804. thisVariable->mUnassignedFieldFlags = 0;
  16805. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16806. }
  16807. }
  16808. targetType = NULL;
  16809. }
  16810. }
  16811. auto autoComplete = mCompiler->GetAutoComplete();
  16812. if ((targetType != NULL) && (!mCurTypeInstance->IsAnonymousInitializerType()))
  16813. {
  16814. BfAstNode* refNode = methodDeclaration;
  16815. if (refNode == NULL)
  16816. refNode = typeDef->mTypeDeclaration;
  16817. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  16818. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  16819. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16820. {
  16821. auto invocationExpr = ctorInvocation;
  16822. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  16823. }
  16824. BfType* targetThisType = targetType;
  16825. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  16826. BfExprEvaluator exprEvaluator(this);
  16827. BfResolvedArgs argValues;
  16828. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16829. {
  16830. argValues.Init(&ctorInvocation->mArguments);
  16831. if (gDebugStuff)
  16832. {
  16833. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  16834. }
  16835. }
  16836. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  16837. BfAllowAppendKind allowAppendKind = GetBaseAllowAppend(mCurMethodInstance);
  16838. BfTypedValue appendIdxVal;
  16839. if (methodDef->HasAppend())
  16840. {
  16841. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  16842. BF_ASSERT(localVar->mName == "__appendIdx");
  16843. auto intRefType = localVar->mResolvedType;
  16844. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  16845. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  16846. }
  16847. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), allowAppendKind, &appendIdxVal);
  16848. if (autoComplete != NULL)
  16849. {
  16850. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  16851. {
  16852. if (autoComplete->mMethodMatchInfo != NULL)
  16853. autoComplete->mIsCapturingMethodMatchInfo = true;
  16854. else
  16855. autoComplete->mIsCapturingMethodMatchInfo = false;
  16856. }
  16857. else
  16858. autoComplete->mIsCapturingMethodMatchInfo = false;
  16859. }
  16860. }
  16861. auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration);
  16862. if ((autoComplete != NULL) && (autoComplete->CheckFixit(methodDeclaration)) && (methodDeclaration != NULL) && (autoCtorDecl != NULL))
  16863. {
  16864. auto typeDecl = methodDef->mDeclaringType->mTypeDeclaration;
  16865. BfParserData* parser = typeDecl->GetSourceData()->ToParserData();
  16866. if (parser != NULL)
  16867. {
  16868. String fixitStr = "Expand auto constructor\t";
  16869. int insertPos = typeDecl->mSrcStart;
  16870. bool needsBlock = false;
  16871. if (auto defBlock = BfNodeDynCast<BfBlock>(typeDecl->mDefineNode))
  16872. {
  16873. insertPos = defBlock->mOpenBrace->mSrcStart + 1;
  16874. }
  16875. else if (auto tokenNode = BfNodeDynCast<BfTokenNode>(typeDecl->mDefineNode))
  16876. {
  16877. insertPos = tokenNode->mSrcStart;
  16878. fixitStr += StrFormat("delete|%s-%d|\x01",
  16879. autoComplete->FixitGetLocation(parser, tokenNode->mSrcStart).c_str(), tokenNode->mSrcEnd - tokenNode->mSrcStart);
  16880. needsBlock = true;
  16881. }
  16882. int srcStart = methodDeclaration->mSrcStart;
  16883. if ((autoCtorDecl->mPrefix == NULL) && (typeDecl->mColonToken != NULL))
  16884. srcStart = typeDecl->mColonToken->mSrcStart;
  16885. while ((srcStart > 0) && (::isspace((uint8)parser->mSrc[srcStart - 1])))
  16886. srcStart--;
  16887. fixitStr += StrFormat("expand|%s|%d|",
  16888. parser->mFileName.c_str(), insertPos);
  16889. if (needsBlock)
  16890. fixitStr += "\t";
  16891. else
  16892. fixitStr += "\f";
  16893. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16894. {
  16895. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16896. paramStr.Replace('\n', '\r');
  16897. fixitStr += "public ";
  16898. fixitStr += paramStr;
  16899. fixitStr += ";\r";
  16900. }
  16901. fixitStr += "\rpublic this(";
  16902. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16903. {
  16904. if (paramIdx > 0)
  16905. fixitStr += ", ";
  16906. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16907. paramStr.Replace('\n', '\r');
  16908. fixitStr += paramStr;
  16909. }
  16910. fixitStr += ")\t";
  16911. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16912. {
  16913. if (paramIdx > 0)
  16914. fixitStr += "\r";
  16915. auto nameNode = autoCtorDecl->mParams[paramIdx]->mNameNode;
  16916. if (nameNode == NULL)
  16917. continue;
  16918. String nameStr = nameNode->ToString();
  16919. fixitStr += "this.";
  16920. fixitStr += nameStr;
  16921. fixitStr += " = ";
  16922. fixitStr += nameStr;
  16923. fixitStr += ";";
  16924. }
  16925. fixitStr += "\b";
  16926. if (needsBlock)
  16927. fixitStr += "\b";
  16928. fixitStr += StrFormat("\x01""delete|%s-%d|",
  16929. autoComplete->FixitGetLocation(parser, srcStart).c_str(), autoCtorDecl->mSrcEnd - srcStart);
  16930. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", fixitStr.c_str()));
  16931. }
  16932. }
  16933. }
  16934. void BfModule::EmitEnumToStringBody()
  16935. {
  16936. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16937. auto strVal = CreateAlloca(stringType);
  16938. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  16939. BfExprEvaluator exprEvaluator(this);
  16940. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16941. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  16942. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  16943. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  16944. BfType* discriminatorType = NULL;
  16945. BfTypedValue rawPayload;
  16946. BfIRValue enumVal;
  16947. if (mCurTypeInstance->IsPayloadEnum())
  16948. {
  16949. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  16950. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  16951. enumTypedValue = LoadValue(enumTypedValue);
  16952. enumVal = enumTypedValue.mValue;
  16953. rawPayload = ExtractValue(GetThis(), NULL, 1);
  16954. }
  16955. else
  16956. enumVal = LoadValue(GetThis()).mValue;
  16957. Array<BfType*> paramTypes;
  16958. paramTypes.Add(stringType);
  16959. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16960. BfIRValue switchVal;
  16961. if (!mCurTypeInstance->IsValuelessType())
  16962. switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  16963. HashSet<int64> handledCases;
  16964. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16965. {
  16966. if (fieldInstance.mIsEnumPayloadCase)
  16967. {
  16968. int tagId = -fieldInstance.mDataIdx - 1;
  16969. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16970. mBfIRBuilder->AddBlock(caseBlock);
  16971. mBfIRBuilder->SetInsertPoint(caseBlock);
  16972. BF_ASSERT(discriminatorType->IsPrimitiveType());
  16973. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  16974. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16975. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16976. auto stringDestVal = LoadValue(stringDestAddr);
  16977. SizedArray<BfIRValue, 2> args;
  16978. args.Add(stringDestVal.mValue);
  16979. args.Add(caseStr);
  16980. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16981. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  16982. BF_ASSERT(payloadType->IsTuple());
  16983. if (payloadType->mFieldInstances.size() != 0)
  16984. {
  16985. auto payload = rawPayload;
  16986. if (payload.mType != payloadType)
  16987. {
  16988. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  16989. }
  16990. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  16991. SizedArray<BfIRValue, 2> irArgs;
  16992. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  16993. stringDestVal = LoadValue(stringDestAddr);
  16994. irArgs.Add(stringDestVal.mValue);
  16995. exprEvaluator.CreateCall(NULL, toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  16996. }
  16997. mBfIRBuilder->CreateBr(endBlock);
  16998. continue;
  16999. }
  17000. if (fieldInstance.mConstIdx == -1)
  17001. continue;
  17002. // Only allow compact 'ValA, ValB' enum declaration fields through
  17003. auto fieldDef = fieldInstance.GetFieldDef();
  17004. auto fieldDecl = fieldDef->mFieldDeclaration;
  17005. if ((fieldDecl == NULL) || (fieldDef->mTypeRef != NULL))
  17006. continue;
  17007. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  17008. if (!handledCases.TryAdd(constant->mInt64, NULL))
  17009. {
  17010. // Duplicate
  17011. continue;
  17012. }
  17013. if (switchVal)
  17014. {
  17015. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  17016. mBfIRBuilder->AddBlock(caseBlock);
  17017. mBfIRBuilder->SetInsertPoint(caseBlock);
  17018. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  17019. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  17020. }
  17021. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  17022. mBfIRBuilder->CreateStore(caseStr, strVal);
  17023. mBfIRBuilder->CreateBr(appendBlock);
  17024. }
  17025. mBfIRBuilder->AddBlock(appendBlock);
  17026. mBfIRBuilder->SetInsertPoint(appendBlock);
  17027. SizedArray<BfIRValue, 2> args;
  17028. auto stringDestVal = LoadValue(stringDestAddr);
  17029. args.Add(stringDestVal.mValue);
  17030. args.Add(mBfIRBuilder->CreateLoad(strVal));
  17031. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  17032. if (switchVal)
  17033. {
  17034. mBfIRBuilder->CreateBr(endBlock);
  17035. mBfIRBuilder->AddBlock(noMatchBlock);
  17036. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  17037. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  17038. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  17039. args.clear();
  17040. args.Add(int64Val);
  17041. stringDestVal = LoadValue(stringDestAddr);
  17042. args.Add(stringDestVal.mValue);
  17043. exprEvaluator.CreateCall(NULL, toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  17044. mBfIRBuilder->CreateBr(endBlock);
  17045. mBfIRBuilder->AddBlock(endBlock);
  17046. mBfIRBuilder->SetInsertPoint(endBlock);
  17047. }
  17048. }
  17049. void BfModule::EmitTupleToStringBody()
  17050. {
  17051. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  17052. BfExprEvaluator exprEvaluator(this);
  17053. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  17054. Array<BfType*> paramTypes;
  17055. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  17056. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  17057. paramTypes.Clear();
  17058. paramTypes.Add(stringType);
  17059. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  17060. auto _AppendChar = [&](char c)
  17061. {
  17062. SizedArray<BfIRValue, 2> args;
  17063. auto stringDestVal = LoadValue(stringDestRef);
  17064. args.Add(stringDestVal.mValue);
  17065. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  17066. exprEvaluator.CreateCall(NULL, appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  17067. };
  17068. int fieldIdx = 0;
  17069. auto thisValue = GetThis();
  17070. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  17071. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  17072. BfIRValue commaStr;
  17073. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  17074. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  17075. _AppendChar('(');
  17076. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  17077. {
  17078. if (fieldInstance.mDataIdx == -1)
  17079. continue;
  17080. if (fieldIdx > 0)
  17081. {
  17082. if (!commaStr)
  17083. commaStr = GetStringObjectValue(", ");
  17084. SizedArray<BfIRValue, 2> args;
  17085. auto stringDestVal = LoadValue(stringDestRef);
  17086. args.Add(stringDestVal.mValue);
  17087. args.Add(commaStr);
  17088. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  17089. }
  17090. fieldIdx++;
  17091. if (fieldInstance.mResolvedType->IsValuelessType())
  17092. continue;
  17093. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  17094. if (fieldValue.mType->IsWrappableType())
  17095. {
  17096. auto wrappedType = GetWrappedStructType(fieldValue.mType);
  17097. if ((wrappedType->IsTypedPrimitive()) || (wrappedType->IsValuelessType()))
  17098. {
  17099. fieldValue.mType = wrappedType;
  17100. }
  17101. else
  17102. {
  17103. fieldValue = MakeAddressable(fieldValue, false, true);
  17104. fieldValue.mType = wrappedType;
  17105. fieldValue.mValue = mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapTypeInstPtr(fieldValue.mType->ToTypeInstance()));
  17106. if (!wrappedType->IsValuelessType())
  17107. fieldValue.mKind = BfTypedValueKind_Addr;
  17108. }
  17109. }
  17110. auto typeInstance = fieldValue.mType->ToTypeInstance();
  17111. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  17112. {
  17113. BfExprEvaluator exprEvaluator(this);
  17114. SizedArray<BfResolvedArg, 0> resolvedArgs;
  17115. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  17116. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  17117. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  17118. methodMatcher.TryDevirtualizeCall(fieldValue);
  17119. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  17120. BfResolvedArg resolvedArg;
  17121. auto stringDestVal = LoadValue(stringDestRef);
  17122. resolvedArg.mTypedValue = stringDestVal;
  17123. resolvedArg.mResolvedType = stringDestVal.mType;
  17124. resolvedArgs.Add(resolvedArg);
  17125. exprEvaluator.CreateCall(&methodMatcher, callVal);
  17126. continue;
  17127. }
  17128. if (fieldValue.mType->IsObjectOrInterface())
  17129. {
  17130. fieldValue = LoadValue(fieldValue);
  17131. BF_ASSERT(!fieldValue.IsAddr());
  17132. SizedArray<BfIRValue, 2> args;
  17133. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  17134. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  17135. stringDestVal = LoadValue(stringDestVal);
  17136. args.Add(stringDestVal.mValue);
  17137. exprEvaluator.CreateCall(NULL, toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  17138. continue;
  17139. }
  17140. BfExprEvaluator exprEvaluator(this);
  17141. SizedArray<BfResolvedArg, 0> resolvedArgs;
  17142. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  17143. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  17144. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  17145. methodMatcher.TryDevirtualizeCall(fieldValue);
  17146. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  17147. {
  17148. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  17149. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  17150. // Just append the type name
  17151. String typeName = TypeToString(fieldInstance.mResolvedType);
  17152. auto strVal = GetStringObjectValue(typeName);
  17153. SizedArray<BfIRValue, 2> args;
  17154. auto stringDestVal = LoadValue(stringDestRef);
  17155. args.Add(stringDestVal.mValue);
  17156. args.Add(strVal);
  17157. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  17158. continue;
  17159. }
  17160. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  17161. BfResolvedArg resolvedArg;
  17162. auto stringDestVal = LoadValue(stringDestRef);
  17163. resolvedArg.mTypedValue = stringDestVal;
  17164. resolvedArg.mResolvedType = stringDestVal.mType;
  17165. resolvedArgs.Add(resolvedArg);
  17166. exprEvaluator.CreateCall(&methodMatcher, callVal);
  17167. }
  17168. _AppendChar(')');
  17169. }
  17170. void BfModule::EmitIteratorBlock(bool& skipBody)
  17171. {
  17172. auto methodInstance = mCurMethodInstance;
  17173. auto methodDef = methodInstance->mMethodDef;
  17174. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17175. auto typeDef = mCurTypeInstance->mTypeDef;
  17176. BfType* innerRetType = NULL;
  17177. BfTypeInstance* usingInterface = NULL;
  17178. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  17179. if (retTypeInst != NULL)
  17180. {
  17181. if ((retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef)) ||
  17182. (retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumeratorTypeDef)))
  17183. {
  17184. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  17185. }
  17186. }
  17187. if (innerRetType == NULL)
  17188. {
  17189. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  17190. return;
  17191. }
  17192. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  17193. if (blockBody == NULL)
  17194. return;
  17195. }
  17196. void BfModule::EmitGCMarkAppended(BfTypedValue markVal)
  17197. {
  17198. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  17199. if (gcType == NULL)
  17200. return;
  17201. BfModuleMethodInstance markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "MarkAppendedObject", 1);
  17202. if (!markFromGCThreadMethodInstance)
  17203. return;
  17204. SizedArray<BfIRValue, 1> args;
  17205. args.push_back(mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  17206. BfExprEvaluator exprEvaluator(this);
  17207. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  17208. }
  17209. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  17210. {
  17211. auto fieldType = markVal.mType;
  17212. auto fieldTypeInst = fieldType->ToTypeInstance();
  17213. if (fieldType == NULL)
  17214. return;
  17215. if (!markVal.mType->IsComposite())
  17216. markVal = LoadValue(markVal);
  17217. BfExprEvaluator exprEvaluator(this);
  17218. PopulateType(markVal.mType, BfPopulateType_Data);
  17219. if (markVal.mType->IsObjectOrInterface())
  17220. {
  17221. BfIRValue val = markVal.mValue;
  17222. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  17223. SizedArray<BfIRValue, 1> args;
  17224. args.push_back(val);
  17225. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  17226. }
  17227. else if (fieldType->IsSizedArray())
  17228. {
  17229. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)fieldType;
  17230. if (sizedArrayType->mElementType->WantsGCMarking())
  17231. {
  17232. BfTypedValue arrayValue = markVal;
  17233. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  17234. auto itr = CreateAlloca(intPtrType);
  17235. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  17236. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  17237. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  17238. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  17239. mBfIRBuilder->CreateBr(loopBB);
  17240. mBfIRBuilder->SetInsertPoint(loopBB);
  17241. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  17242. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  17243. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  17244. mBfIRBuilder->SetInsertPoint(bodyBB);
  17245. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17246. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17247. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  17248. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17249. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17250. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  17251. mBfIRBuilder->CreateStore(incValue, itr);
  17252. mBfIRBuilder->CreateBr(loopBB);
  17253. mBfIRBuilder->SetInsertPoint(doneBB);
  17254. }
  17255. }
  17256. else if ((fieldType->IsComposite()) && (!fieldType->IsTypedPrimitive()) && (fieldTypeInst != NULL))
  17257. {
  17258. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  17259. if (markMemberMethodInstance)
  17260. {
  17261. SizedArray<BfIRValue, 1> args;
  17262. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  17263. if (markVal.mType != methodOwner)
  17264. markVal = Cast(NULL, markVal, methodOwner);
  17265. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  17266. exprEvaluator.CreateCall(NULL, markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  17267. }
  17268. }
  17269. }
  17270. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  17271. {
  17272. Array<BfMethodInstance*> methodInstances;
  17273. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17274. {
  17275. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  17276. auto chainedMethodInst = methodInstGroup.mDefault;
  17277. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  17278. {
  17279. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  17280. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  17281. {
  17282. methodInstances.push_back(chainedMethodInst);
  17283. }
  17284. }
  17285. }
  17286. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  17287. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  17288. {
  17289. bool isBetter;
  17290. bool isWorse;
  17291. CompareDeclTypes(mCurTypeInstance, lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  17292. if (isBetter == isWorse)
  17293. {
  17294. return false;
  17295. }
  17296. return isWorse;
  17297. });
  17298. if (reverse)
  17299. std::reverse(methodInstances.begin(), methodInstances.end());
  17300. for (auto chainedMethodInst : methodInstances)
  17301. {
  17302. auto declModule = this;
  17303. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  17304. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  17305. BfExprEvaluator exprEvaluator(this);
  17306. SizedArray<BfIRValue, 1> args;
  17307. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  17308. exprEvaluator.CreateCall(NULL, moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  17309. }
  17310. }
  17311. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  17312. {
  17313. BF_ASSERT(mCurMethodInstance->mIsReified);
  17314. if (mCurTypeInstance->mHotTypeData == NULL)
  17315. {
  17316. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  17317. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  17318. }
  17319. auto hotMethod = mCurMethodInstance->mHotMethod;
  17320. for (auto depData : hotMethod->mReferences)
  17321. {
  17322. // Only virtual decls are allowed to already be there
  17323. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  17324. }
  17325. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  17326. int prevSize = (int)hotMethod->mReferences.size();
  17327. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  17328. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  17329. refCount++;
  17330. hotMethod->mReferences.Reserve(refCount);
  17331. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  17332. {
  17333. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  17334. hotThis->mRefCount++;
  17335. hotMethod->mReferences.Insert(0, hotThis);
  17336. prevSize++;
  17337. }
  17338. for (auto val : builder->mAllocatedData)
  17339. {
  17340. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  17341. hotMethod->mReferences.Add(hotAllocation);
  17342. }
  17343. for (auto val : builder->mUsedData)
  17344. hotMethod->mReferences.Add(val);
  17345. for (auto val : builder->mCalledMethods)
  17346. hotMethod->mReferences.Add(val);
  17347. for (auto val : builder->mDevirtualizedCalledMethods)
  17348. {
  17349. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  17350. hotMethod->mReferences.Add(devirtualizedMethod);
  17351. }
  17352. for (auto val : builder->mFunctionPtrs)
  17353. {
  17354. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  17355. hotMethod->mReferences.Add(funcRef);
  17356. }
  17357. for (auto val : builder->mInnerMethods)
  17358. {
  17359. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  17360. hotMethod->mReferences.Add(innerMethod);
  17361. }
  17362. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  17363. {
  17364. auto depData = hotMethod->mReferences[refIdx];
  17365. BF_ASSERT(depData != NULL);
  17366. depData->mRefCount++;
  17367. }
  17368. }
  17369. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  17370. {
  17371. auto methodDef = methodInstance->mMethodDef;
  17372. auto methodDeclaration = methodDef->mMethodDeclaration;
  17373. bool isThisStruct = false;
  17374. if (thisType != NULL)
  17375. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  17376. int argIdx = 0;
  17377. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  17378. argIdx++;
  17379. auto rootMethodState = mCurMethodState->GetRootMethodState();
  17380. if (!methodDef->mIsStatic)
  17381. {
  17382. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17383. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17384. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  17385. paramVar->mIsBumpAlloc = true;
  17386. paramVar->mResolvedType = thisType;
  17387. paramVar->mName.Reference("this");
  17388. if (!thisType->IsValuelessType())
  17389. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  17390. else
  17391. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  17392. if ((!mIsComptimeModule) && (thisType->IsSplattable()) && (methodInstance->AllowsSplatting(-1)))
  17393. {
  17394. if (!thisType->IsTypedPrimitive())
  17395. paramVar->mIsSplat = true;
  17396. }
  17397. else if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (!methodInstance->ForcingThisPtr()))
  17398. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  17399. auto thisTypeInst = thisType->ToTypeInstance();
  17400. paramVar->mIsStruct = isThisStruct;
  17401. paramVar->mAddr = BfIRValue();
  17402. paramVar->mIsThis = true;
  17403. paramVar->mParamIdx = -1;
  17404. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  17405. {
  17406. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  17407. }
  17408. else
  17409. {
  17410. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  17411. }
  17412. paramVar->mReadFromId = -1;
  17413. paramVar->Init();
  17414. if (methodDeclaration == NULL)
  17415. UseDefaultSrcPos();
  17416. AddLocalVariableDef(paramVar);
  17417. if (!thisType->IsValuelessType())
  17418. {
  17419. if (wantsDIData)
  17420. {
  17421. BfType* thisPtrType = thisType;
  17422. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  17423. if (!thisType->IsValueType())
  17424. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  17425. else if (!paramVar->mIsSplat)
  17426. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  17427. diParams->push_back(diType);
  17428. }
  17429. if (paramVar->mIsSplat)
  17430. {
  17431. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17432. }
  17433. else
  17434. {
  17435. argIdx++;
  17436. if (loweredTypeCode2 != BfTypeCode_None)
  17437. argIdx++;
  17438. }
  17439. }
  17440. }
  17441. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  17442. argIdx++;
  17443. bool hadParams = false;
  17444. bool hasDefault = false;
  17445. int compositeVariableIdx = -1;
  17446. int paramIdx = 0;
  17447. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  17448. {
  17449. // We already issues a type error for this param if we had one in declaration processing
  17450. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  17451. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  17452. paramVar->mIsBumpAlloc = true;
  17453. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17454. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17455. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  17456. auto resolvedType = methodInstance->GetParamType(paramIdx);
  17457. if (resolvedType == NULL)
  17458. {
  17459. AssertErrorState();
  17460. paramVar->mParamFailed = true;
  17461. }
  17462. prevIgnoreErrors.Restore();
  17463. PopulateType(resolvedType, BfPopulateType_Declaration);
  17464. paramVar->mResolvedType = resolvedType;
  17465. int namePrefixCount = 0;
  17466. methodInstance->GetParamName(paramIdx, paramVar->mName, namePrefixCount);
  17467. paramVar->mNamePrefixCount = (uint8)namePrefixCount;
  17468. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  17469. if (!isParamSkipped)
  17470. {
  17471. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  17472. if (resolvedType->IsMethodRef())
  17473. {
  17474. paramVar->mIsSplat = true;
  17475. }
  17476. else if ((!mIsComptimeModule) && (resolvedType->IsComposite()) && (resolvedType->IsSplattable()))
  17477. {
  17478. if (methodInstance->AllowsSplatting(paramIdx))
  17479. {
  17480. auto resolveTypeInst = resolvedType->ToTypeInstance();
  17481. if ((resolveTypeInst != NULL) && (resolveTypeInst->mIsCRepr))
  17482. paramVar->mIsSplat = true;
  17483. else
  17484. {
  17485. int splatCount = resolvedType->GetSplatCount();
  17486. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  17487. paramVar->mIsSplat = true;
  17488. }
  17489. }
  17490. }
  17491. }
  17492. else
  17493. {
  17494. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  17495. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  17496. }
  17497. paramVar->mIsLowered = (!mIsComptimeModule) && resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  17498. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  17499. paramVar->mParamIdx = paramIdx;
  17500. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  17501. paramVar->mReadFromId = 0;
  17502. if (resolvedType->IsRef())
  17503. {
  17504. auto refType = (BfRefType*)resolvedType;
  17505. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  17506. if (refType->mRefKind == BfRefType::RefKind_In)
  17507. {
  17508. paramVar->mIsReadOnly = true;
  17509. }
  17510. }
  17511. else
  17512. {
  17513. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  17514. if (methodDef->mMethodType != BfMethodType_Mixin)
  17515. paramVar->mIsReadOnly = true;
  17516. }
  17517. if (paramVar->mResolvedType->IsGenericParam())
  17518. {
  17519. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  17520. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  17521. {
  17522. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  17523. paramVar->mResolvedType = typedVal.mType;
  17524. paramVar->mConstValue = typedVal.mValue;
  17525. }
  17526. }
  17527. if (paramVar->mResolvedType->IsConstExprValue())
  17528. {
  17529. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  17530. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  17531. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  17532. BF_ASSERT(unspecParamType->IsGenericParam());
  17533. if (unspecParamType->IsGenericParam())
  17534. {
  17535. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  17536. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  17537. {
  17538. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  17539. if (genericParamInst->mTypeConstraint != NULL)
  17540. {
  17541. BfExprEvaluator exprEvaluator(this);
  17542. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  17543. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  17544. auto checkType = genericParamInst->mTypeConstraint;
  17545. if (checkType->IsTypedPrimitive())
  17546. checkType = checkType->GetUnderlyingType();
  17547. auto typedVal = exprEvaluator.mResult;
  17548. if ((typedVal) && (typedVal.mType != checkType))
  17549. typedVal = Cast(NULL, typedVal, checkType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  17550. if ((typedVal.mType == checkType) && (typedVal.mValue.IsConst()))
  17551. {
  17552. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  17553. paramVar->mConstValue = typedVal.mValue;
  17554. BF_ASSERT(paramVar->mConstValue.IsConst());
  17555. paramVar->mIsConst = true;
  17556. }
  17557. else
  17558. {
  17559. AssertErrorState();
  17560. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  17561. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  17562. paramVar->mIsConst = true;
  17563. }
  17564. if (paramVar->mResolvedType->IsObject())
  17565. {
  17566. BfTypedValue typedVal(paramVar->mConstValue, paramVar->mResolvedType);
  17567. FixValueActualization(typedVal);
  17568. if (typedVal.mValue.IsConst())
  17569. paramVar->mConstValue = typedVal.mValue;
  17570. }
  17571. }
  17572. }
  17573. }
  17574. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  17575. if (paramVar->mResolvedType->IsConstExprValue())
  17576. {
  17577. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  17578. //AssertErrorState();
  17579. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  17580. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  17581. paramVar->mIsConst = true;
  17582. }
  17583. }
  17584. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  17585. {
  17586. if (compositeVariableIdx == -1)
  17587. {
  17588. auto paramInst = &methodInstance->mParams[paramIdx];
  17589. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  17590. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  17591. BfLocalVariable* localVar = new BfLocalVariable();
  17592. localVar->mName = paramDef->mName;
  17593. localVar->mNamePrefixCount = paramDef->mNamePrefixCount;
  17594. if (paramDef->mTypeRef != NULL)
  17595. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  17596. if (localVar->mResolvedType == NULL)
  17597. localVar->mResolvedType = GetPrimitiveType(BfTypeCode_None);
  17598. localVar->mCompositeCount = 0;
  17599. DoAddLocalVariable(localVar);
  17600. }
  17601. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  17602. paramVar->mIsImplicitParam = true;
  17603. }
  17604. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params)
  17605. {
  17606. if ((paramVar->mResolvedType->IsModifiedTypeType()) && (((BfModifiedTypeType*)paramVar->mResolvedType)->mModifiedKind == BfToken_Params))
  17607. {
  17608. paramVar->mValue = BfIRValue();
  17609. paramVar->mCompositeCount = 0;
  17610. paramVar->mIsSplat = false;
  17611. }
  17612. }
  17613. if (!mCurTypeInstance->IsDelegateOrFunction())
  17614. CheckVariableDef(paramVar);
  17615. paramVar->Init();
  17616. AddLocalVariableDef(paramVar);
  17617. if (!isParamSkipped)
  17618. {
  17619. if (wantsDIData)
  17620. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  17621. if (paramVar->mIsSplat)
  17622. {
  17623. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17624. }
  17625. else
  17626. {
  17627. argIdx++;
  17628. }
  17629. if (loweredTypeCode2 != BfTypeCode_None)
  17630. argIdx++;
  17631. }
  17632. }
  17633. // Try to find an ending delegate params composite
  17634. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  17635. {
  17636. auto paramDef = methodDef->mParams.back();
  17637. if (paramDef->mParamKind == BfParamKind_Params)
  17638. {
  17639. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  17640. if (paramsType == NULL)
  17641. {
  17642. // Had error or 'var'
  17643. }
  17644. else if (paramsType->IsGenericParam())
  17645. {
  17646. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  17647. if (genericParamInstance->mTypeConstraint != NULL)
  17648. {
  17649. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  17650. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) || (genericParamInstance->mTypeConstraint->IsTuple()) ||
  17651. ((typeInstConstraint != NULL) &&
  17652. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mTupleTypeDef)))))
  17653. {
  17654. bool doAdd = true;
  17655. // TODO: Remove
  17656. if (!mCurMethodState->mLocals.IsEmpty())
  17657. {
  17658. auto checkVar = mCurMethodState->mLocals.back();
  17659. if (checkVar->mName == paramDef->mName)
  17660. doAdd = false;
  17661. }
  17662. if (doAdd)
  17663. {
  17664. BfLocalVariable* localVar = new BfLocalVariable();
  17665. localVar->mName = paramDef->mName;
  17666. localVar->mResolvedType = paramsType;
  17667. localVar->mCompositeCount = 0;
  17668. DoAddLocalVariable(localVar);
  17669. }
  17670. }
  17671. }
  17672. }
  17673. else if (paramsType->IsDelegate())
  17674. {
  17675. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  17676. if (invokeMethodInstance != NULL)
  17677. {
  17678. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  17679. // and wasn't cleared by the preceding loop
  17680. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  17681. BfLocalVariable* localVar = new BfLocalVariable();
  17682. localVar->mName = paramDef->mName;
  17683. localVar->mResolvedType = paramsType;
  17684. localVar->mCompositeCount = 0;
  17685. DoAddLocalVariable(localVar);
  17686. }
  17687. }
  17688. }
  17689. }
  17690. }
  17691. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  17692. {
  17693. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  17694. // return;
  17695. auto startMethodState = mCurMethodState;
  17696. auto _ClearState = [&]()
  17697. {
  17698. mCurMethodState->mLocalMethods.Clear();
  17699. for (auto& local : mCurMethodState->mLocals)
  17700. {
  17701. if (local->mIsBumpAlloc)
  17702. local->~BfLocalVariable();
  17703. else
  17704. delete local;
  17705. }
  17706. mCurMethodState->mLocals.Clear();
  17707. mCurMethodState->mLocalVarSet.Clear();
  17708. };
  17709. while (true)
  17710. {
  17711. bool didWork = false;
  17712. // 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
  17713. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  17714. // however (compiler bug), so this is the safest way
  17715. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  17716. {
  17717. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  17718. {
  17719. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  17720. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  17721. if (!mHadBuildError)
  17722. {
  17723. // Process as a closure - that allows us to look back and see the const locals and stuff
  17724. BfClosureState closureState;
  17725. mCurMethodState->mClosureState = &closureState;
  17726. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17727. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  17728. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  17729. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  17730. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  17731. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17732. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  17733. _ClearState();
  17734. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  17735. {
  17736. auto localVar = new BfLocalVariable();
  17737. *localVar = constLocal;
  17738. DoAddLocalVariable(localVar);
  17739. }
  17740. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  17741. bool doProcess = !mCompiler->mCanceling;
  17742. if (doProcess)
  17743. {
  17744. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  17745. ProcessMethod(deferredLocalMethod->mMethodInstance);
  17746. }
  17747. }
  17748. delete deferredLocalMethod;
  17749. mContext->CheckLockYield();
  17750. didWork = true;
  17751. }
  17752. mCurMethodState->mDeferredLocalMethods.Clear();
  17753. }
  17754. for (auto& kv : mCurMethodState->mLocalMethodCache)
  17755. {
  17756. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  17757. }
  17758. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  17759. {
  17760. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  17761. {
  17762. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  17763. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  17764. BfClosureState closureState;
  17765. mCurMethodState->mClosureState = &closureState;
  17766. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17767. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  17768. if (lambdaInstance->mClosureTypeInstance != NULL)
  17769. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  17770. else
  17771. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  17772. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17773. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  17774. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  17775. _ClearState();
  17776. for (auto& constLocal : lambdaInstance->mConstLocals)
  17777. {
  17778. //if (constLocal.mIsThis)
  17779. {
  17780. // Valueless 'this'
  17781. closureState.mConstLocals.Add(constLocal);
  17782. }
  17783. /*else
  17784. {
  17785. auto localVar = new BfLocalVariable();
  17786. *localVar = constLocal;
  17787. DoAddLocalVariable(localVar);
  17788. }*/
  17789. }
  17790. BfMethodInstanceGroup methodInstanceGroup;
  17791. methodInstanceGroup.mOwner = mCurTypeInstance;
  17792. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  17793. bool doProcess = !mCompiler->mCanceling;
  17794. if (doProcess)
  17795. {
  17796. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  17797. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17798. ProcessMethod(lambdaInstance->mMethodInstance);
  17799. lambdaInstance->mMethodInstance->mMethodInstanceGroup = NULL;
  17800. if (lambdaInstance->mDtorMethodInstance != NULL)
  17801. {
  17802. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17803. auto startMethodState2 = mCurMethodState;
  17804. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  17805. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = NULL;
  17806. }
  17807. }
  17808. didWork = true;
  17809. }
  17810. mContext->CheckLockYield();
  17811. mCurMethodState->mDeferredLambdaInstances.Clear();
  17812. }
  17813. if (!didWork)
  17814. break;
  17815. }
  17816. }
  17817. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance, bool isAppendObject)
  17818. {
  17819. if (checkType->IsComposite())
  17820. PopulateType(checkType, BfPopulateType_Data);
  17821. if (!checkType->WantsGCMarking())
  17822. return;
  17823. if (checkType->IsDeleting())
  17824. {
  17825. mCompiler->RequestExtraCompile();
  17826. InternalError("EmitGCMarkValue deleted type");
  17827. return;
  17828. }
  17829. auto typeInstance = checkType->ToTypeInstance();
  17830. bool callMarkMethod = false;
  17831. // Call the actual marking method
  17832. if (memberDepth == 0)
  17833. {
  17834. // Don't call marking method on self
  17835. }
  17836. else if (checkType->IsObjectOrInterface())
  17837. {
  17838. if (!objectOffsets.Add(curOffset))
  17839. {
  17840. return;
  17841. }
  17842. callMarkMethod = true;
  17843. }
  17844. else if (checkType->IsSizedArray())
  17845. {
  17846. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  17847. if (sizedArrayType->mElementType->WantsGCMarking())
  17848. {
  17849. BfTypedValue arrayValue = thisValue;
  17850. if (thisValue.mType != checkType)
  17851. {
  17852. BfIRValue srcValue = thisValue.mValue;
  17853. if (curOffset != 0)
  17854. {
  17855. if (!thisValue.mType->IsPointer())
  17856. {
  17857. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17858. auto int8PtrType = CreatePointerType(int8Type);
  17859. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  17860. }
  17861. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  17862. }
  17863. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  17864. }
  17865. if (sizedArrayType->mElementCount > 6)
  17866. {
  17867. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  17868. auto itr = CreateAlloca(intPtrType);
  17869. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  17870. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  17871. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  17872. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  17873. mBfIRBuilder->CreateBr(loopBB);
  17874. mBfIRBuilder->SetInsertPoint(loopBB);
  17875. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  17876. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  17877. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  17878. mBfIRBuilder->SetInsertPoint(bodyBB);
  17879. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17880. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17881. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  17882. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17883. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17884. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  17885. mBfIRBuilder->CreateStore(incValue, itr);
  17886. mBfIRBuilder->CreateBr(loopBB);
  17887. mBfIRBuilder->SetInsertPoint(doneBB);
  17888. }
  17889. else
  17890. {
  17891. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  17892. {
  17893. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17894. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17895. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  17896. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17897. HashSet<int> objectOffsets;
  17898. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17899. }
  17900. }
  17901. }
  17902. }
  17903. else if (typeInstance != NULL)
  17904. {
  17905. typeInstance->mTypeDef->PopulateMemberSets();
  17906. BfMemberSetEntry* entry = NULL;
  17907. BfMethodDef* methodDef = NULL;
  17908. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  17909. {
  17910. methodDef = (BfMethodDef*)entry->mMemberDef;
  17911. if (methodDef->HasBody())
  17912. {
  17913. callMarkMethod = true;
  17914. }
  17915. }
  17916. }
  17917. if (callMarkMethod)
  17918. {
  17919. BfTypedValue markValue;
  17920. auto memberType = checkType;
  17921. if (memberType->IsObjectOrInterface())
  17922. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  17923. auto memberPtrType = CreatePointerType(memberType);
  17924. if (curOffset == 0)
  17925. {
  17926. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17927. }
  17928. else
  17929. {
  17930. if (!thisValue.mType->IsPointer())
  17931. {
  17932. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17933. auto int8PtrType = CreatePointerType(int8Type);
  17934. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  17935. }
  17936. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  17937. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17938. }
  17939. if (isAppendObject)
  17940. EmitGCMarkAppended(markValue);
  17941. else
  17942. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17943. return;
  17944. }
  17945. auto methodDef = mCurMethodInstance->mMethodDef;
  17946. if (checkType->IsPayloadEnum())
  17947. {
  17948. for (auto& fieldInst : typeInstance->mFieldInstances)
  17949. {
  17950. if (!fieldInst.mIsEnumPayloadCase)
  17951. continue;
  17952. auto fieldDef = fieldInst.GetFieldDef();
  17953. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17954. }
  17955. return;
  17956. }
  17957. if (typeInstance == NULL)
  17958. return;
  17959. for (auto& fieldInst : typeInstance->mFieldInstances)
  17960. {
  17961. auto fieldDef = fieldInst.GetFieldDef();
  17962. if (fieldDef == NULL)
  17963. continue;
  17964. if (fieldDef->mIsStatic)
  17965. continue;
  17966. if (typeInstance == mCurTypeInstance)
  17967. {
  17968. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  17969. // we may be marking member values that can never contain a value anyway, but this is benign
  17970. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17971. continue;
  17972. }
  17973. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance, fieldInst.IsAppendedObject());
  17974. }
  17975. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  17976. {
  17977. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17978. }
  17979. }
  17980. void BfModule::EmitGCMarkMembers()
  17981. {
  17982. auto methodDef = mCurMethodInstance->mMethodDef;
  17983. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  17984. BfModuleMethodInstance markFromGCThreadMethodInstance;
  17985. if (gcType != NULL)
  17986. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  17987. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  17988. {
  17989. if (mCurTypeInstance->IsBoxed())
  17990. {
  17991. // This already gets filled in by the normal boxed forwarding
  17992. }
  17993. else
  17994. {
  17995. auto thisValue = GetThis();
  17996. if (thisValue.IsSplat())
  17997. {
  17998. BfIRFunction func = mCurMethodInstance->mIRFunction;
  17999. int argIdx = 0;
  18000. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  18001. {
  18002. if (checkType->IsStruct())
  18003. {
  18004. auto checkTypeInstance = checkType->ToTypeInstance();
  18005. if (checkTypeInstance->mBaseType != NULL)
  18006. checkTypeLambda(checkTypeInstance->mBaseType);
  18007. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  18008. {
  18009. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  18010. if (fieldInstance->mDataIdx >= 0)
  18011. checkTypeLambda(fieldInstance->GetResolvedType());
  18012. }
  18013. }
  18014. else if (checkType->IsMethodRef())
  18015. {
  18016. BFMODULE_FATAL(this, "Not handled");
  18017. }
  18018. else if (checkType->WantsGCMarking())
  18019. {
  18020. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  18021. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  18022. argIdx++;
  18023. }
  18024. };
  18025. checkTypeLambda(thisValue.mType);
  18026. }
  18027. else if (!methodDef->mIsStatic)
  18028. {
  18029. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  18030. {
  18031. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  18032. if (moduleMethodInst)
  18033. {
  18034. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  18035. bool wantsBaseMarking = true;
  18036. if (methodBaseType == mContext->mBfObjectType)
  18037. {
  18038. wantsBaseMarking = false;
  18039. PopulateType(methodBaseType);
  18040. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  18041. {
  18042. if ((fieldInstance.GetFieldDef()->mDeclaringType->IsExtension()) &&
  18043. (fieldInstance.mResolvedType->WantsGCMarking()))
  18044. wantsBaseMarking = true;
  18045. }
  18046. }
  18047. if (wantsBaseMarking)
  18048. {
  18049. auto thisValue = GetThis();
  18050. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  18051. SizedArray<BfIRValue, 1> args;
  18052. if ((!mIsComptimeModule) && (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1)))
  18053. {
  18054. BfExprEvaluator exprEvaluator(this);
  18055. exprEvaluator.SplatArgs(baseValue, args);
  18056. }
  18057. else
  18058. {
  18059. args.push_back(baseValue.mValue);
  18060. }
  18061. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  18062. }
  18063. }
  18064. }
  18065. }
  18066. if (!methodDef->mIsStatic)
  18067. {
  18068. HashSet<int> objectOffsets;
  18069. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  18070. }
  18071. else
  18072. {
  18073. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  18074. {
  18075. if (thisValue.IsSplat())
  18076. break;
  18077. auto fieldDef = fieldInst.GetFieldDef();
  18078. if (fieldDef == NULL)
  18079. continue;
  18080. if (IsThreadLocal(&fieldInst))
  18081. continue;
  18082. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  18083. {
  18084. // For extensions, only handle these fields in the appropriate extension
  18085. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  18086. continue;
  18087. if (!fieldInst.mFieldIncluded)
  18088. continue;
  18089. auto fieldType = fieldInst.mResolvedType;
  18090. auto fieldDef = fieldInst.GetFieldDef();
  18091. BfTypedValue markVal;
  18092. if (fieldDef->mIsConst)
  18093. continue;
  18094. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  18095. continue;
  18096. mBfIRBuilder->PopulateType(fieldType);
  18097. if (fieldType->IsValuelessType())
  18098. continue;
  18099. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  18100. {
  18101. StringT<512> staticVarName;
  18102. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  18103. if (staticVarName.StartsWith('#'))
  18104. continue;
  18105. markVal = ReferenceStaticField(&fieldInst);
  18106. }
  18107. else if (!fieldDef->mIsStatic)
  18108. {
  18109. if (fieldInst.IsAppendedObject())
  18110. {
  18111. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst.mDataIdx);
  18112. auto val = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  18113. markVal = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst.mResolvedType)), fieldInst.mResolvedType);
  18114. }
  18115. else
  18116. {
  18117. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  18118. }
  18119. }
  18120. if (markVal)
  18121. {
  18122. if ((fieldInst.IsAppendedObject()) && (!fieldDef->mIsStatic))
  18123. EmitGCMarkAppended(markVal);
  18124. else
  18125. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  18126. }
  18127. }
  18128. }
  18129. }
  18130. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  18131. CallChainedMethods(mCurMethodInstance, false);
  18132. }
  18133. }
  18134. // If there are appends then we just need the rootmost append type to do the Dbg_MarkAppended
  18135. if ((!mIsComptimeModule) && (!methodDef->mIsStatic) && (mCompiler->mOptions.mDebugAlloc) &&
  18136. (mCurTypeInstance->HasAppendCtor()) && (!mCurTypeInstance->BaseHasAppendCtor()))
  18137. {
  18138. auto thisValue = GetThis();
  18139. auto appendedObj = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  18140. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_MarkAppended", 1);
  18141. SizedArray<BfIRValue, 1> llvmArgs;
  18142. llvmArgs.push_back(appendedObj);
  18143. if (allocMethod)
  18144. mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  18145. }
  18146. }
  18147. void BfModule::EmitGCFindTLSMembers()
  18148. {
  18149. auto methodDef = mCurMethodInstance->mMethodDef;
  18150. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  18151. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  18152. BF_ASSERT(reportTLSMark);
  18153. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  18154. {
  18155. auto fieldDef = fieldInst.GetFieldDef();
  18156. if (fieldDef == NULL)
  18157. continue;
  18158. if (!IsThreadLocal(&fieldInst))
  18159. continue;
  18160. // For extensions, only handle these fields in the appropriate extension
  18161. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  18162. continue;
  18163. if (!fieldInst.mFieldIncluded)
  18164. continue;
  18165. if (fieldDef->mIsConst)
  18166. continue;
  18167. auto fieldType = fieldInst.mResolvedType;
  18168. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  18169. continue;
  18170. if (fieldType->IsValuelessType())
  18171. continue;
  18172. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  18173. if (markVal)
  18174. {
  18175. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  18176. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  18177. SizedArray<BfIRValue, 2> llvmArgs;
  18178. llvmArgs.push_back(fieldRefPtr);
  18179. llvmArgs.push_back(markFuncPtr);
  18180. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  18181. }
  18182. }
  18183. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  18184. CallChainedMethods(mCurMethodInstance, false);
  18185. }
  18186. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup, bool forceIRWrites)
  18187. {
  18188. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  18189. if (mIsComptimeModule)
  18190. {
  18191. BF_ASSERT(!mCompiler->IsAutocomplete());
  18192. }
  18193. if (mAwaitingInitFinish)
  18194. FinishInit();
  18195. if ((methodInstance->mIsReified) && (!mCompiler->mIsResolveOnly))
  18196. {
  18197. BfLogSysM("REIFIED(ProcessMethod): %s %p Module: %s\n", methodInstance->mMethodDef->mName.c_str(), methodInstance, mModuleName.c_str());
  18198. }
  18199. // Reify types that are actually used - they don't get reified during method declaration
  18200. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  18201. {
  18202. auto _CheckType = [&](BfType* type)
  18203. {
  18204. if (!type->IsReified())
  18205. PopulateType(type, BfPopulateType_Declaration);
  18206. };
  18207. _CheckType(methodInstance->mReturnType);
  18208. for (auto& param : methodInstance->mParams)
  18209. {
  18210. _CheckType(param.mResolvedType);
  18211. }
  18212. }
  18213. if (!methodInstance->mIsReified)
  18214. BF_ASSERT(!mIsReified);
  18215. BF_ASSERT((!methodInstance->GetOwner()->IsUnspecializedTypeVariation()) || (mIsComptimeModule));
  18216. if (methodInstance->mMethodInfoEx != NULL)
  18217. {
  18218. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  18219. {
  18220. if (methodGenericArg->IsMethodRef())
  18221. {
  18222. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  18223. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  18224. }
  18225. }
  18226. }
  18227. if (mBfIRBuilder == NULL)
  18228. {
  18229. BfLogSysM("ProcessMethod %p calling EnsureIRBuilder\n", methodInstance);
  18230. EnsureIRBuilder();
  18231. }
  18232. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, (mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized) && (!forceIRWrites));
  18233. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  18234. {
  18235. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  18236. }
  18237. SetAndRestoreValue<bool> prevIsClassifying;
  18238. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  18239. (mCompiler->mResolvePassData != NULL))
  18240. {
  18241. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  18242. prevIsClassifying.Init(mCompiler->mResolvePassData->mIsClassifying, false);
  18243. }
  18244. if (methodInstance->mHasBeenProcessed)
  18245. {
  18246. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  18247. return;
  18248. }
  18249. if (methodInstance->mFailedConstraints)
  18250. {
  18251. // The only way this should be able to happen is if we fail our generic param check
  18252. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  18253. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  18254. methodInstance->mHasBeenProcessed = true;
  18255. return;
  18256. }
  18257. if (HasExecutedOutput())
  18258. {
  18259. BF_ASSERT(mIsModuleMutable);
  18260. }
  18261. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  18262. if (!mIsComptimeModule)
  18263. {
  18264. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  18265. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  18266. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  18267. {
  18268. auto owningModule = methodInstance->GetOwner()->mModule;
  18269. if (owningModule->mIsScratchModule)
  18270. {
  18271. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  18272. }
  18273. else
  18274. {
  18275. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  18276. if (owningModule->mOnDemandMethodCount > 0)
  18277. owningModule->mOnDemandMethodCount--;
  18278. }
  18279. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  18280. VerifyOnDemandMethods();
  18281. }
  18282. }
  18283. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  18284. // self-referencing append allocations in ctor@calcAppend
  18285. methodInstance->mHasBeenProcessed = true;
  18286. mIncompleteMethodCount--;
  18287. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  18288. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  18289. auto methodDef = methodInstance->mMethodDef;
  18290. auto methodDeclaration = methodDef->GetMethodDeclaration();
  18291. if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  18292. mBfIRBuilder->mIgnoreWrites = true;
  18293. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  18294. {
  18295. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  18296. // so we get the new vdata for it
  18297. methodInstance->GetOwner()->mDirty = true;
  18298. }
  18299. int dependentGenericStartIdx = 0;
  18300. if ((methodDef->mIsLocalMethod) && (mCurMethodState != NULL)) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  18301. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  18302. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  18303. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  18304. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  18305. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  18306. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  18307. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors);
  18308. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, mIsComptimeModule);
  18309. if ((!mIsComptimeModule) && (methodInstance->mIsReified) &&
  18310. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  18311. {
  18312. mCurTypeInstance->mHasBeenInstantiated = true;
  18313. }
  18314. // Warnings are shown in the capture phase
  18315. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  18316. mIgnoreWarnings = true;
  18317. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  18318. UseDefaultSrcPos();
  18319. if ((mIsComptimeModule) && (methodDef->mIsStatic))
  18320. {
  18321. PopulateType(mCurTypeInstance, BfPopulateType_AllowStaticMethods);
  18322. }
  18323. else
  18324. {
  18325. // We may not actually be populated in relatively rare autocompelte cases
  18326. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  18327. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  18328. }
  18329. BfAstNode* nameNode = NULL;
  18330. if (methodDeclaration != NULL)
  18331. {
  18332. nameNode = methodDeclaration->mNameNode;
  18333. if (nameNode == NULL)
  18334. {
  18335. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  18336. nameNode = ctorDeclaration->mThisToken;
  18337. }
  18338. }
  18339. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  18340. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) &&
  18341. (methodDef->mIdx >= 0) && (!methodInstance->mIsForeignMethodDef))
  18342. {
  18343. if (methodInstance->GetExplicitInterface() == NULL)
  18344. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  18345. else
  18346. {
  18347. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  18348. {
  18349. auto ifaceInst = ifaceEntry.mInterfaceType;
  18350. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  18351. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  18352. if (methodInstance->GetExplicitInterface() != ifaceInst)
  18353. continue;
  18354. ifaceInst->mTypeDef->PopulateMemberSets();
  18355. BfMethodDef* nextMethod = NULL;
  18356. BfMemberSetEntry* entry = NULL;
  18357. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  18358. nextMethod = (BfMethodDef*)entry->mMemberDef;
  18359. while (nextMethod != NULL)
  18360. {
  18361. auto checkMethod = nextMethod;
  18362. nextMethod = nextMethod->mNextWithSameName;
  18363. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  18364. if (implMethodInst == methodInstance)
  18365. {
  18366. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  18367. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  18368. }
  18369. }
  18370. }
  18371. }
  18372. if (methodDef->mIsOverride)
  18373. {
  18374. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  18375. {
  18376. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  18377. if (ventry.mDeclaringMethod.mMethodNum == -1)
  18378. continue;
  18379. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  18380. if (virtMethod != NULL)
  18381. {
  18382. if (virtMethod == methodInstance)
  18383. {
  18384. // Is matching method
  18385. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  18386. {
  18387. auto baseType = mCurTypeInstance->mBaseType;
  18388. if (baseType != NULL)
  18389. {
  18390. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  18391. baseType = baseType->mBaseType;
  18392. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  18393. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  18394. }
  18395. }
  18396. break;
  18397. }
  18398. }
  18399. }
  18400. }
  18401. }
  18402. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d Incomplete:%d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified, mIncompleteMethodCount);
  18403. int importStrNum = -1;
  18404. auto importKind = methodInstance->GetImportKind();
  18405. if ((!mCompiler->mIsResolveOnly) &&
  18406. ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic)))
  18407. {
  18408. if (auto customAttr = methodInstance->GetCustomAttributes()->Get(mCompiler->mImportAttributeTypeDef))
  18409. {
  18410. if (customAttr->mCtorArgs.size() == 1)
  18411. {
  18412. auto fileNameArg = customAttr->mCtorArgs[0];
  18413. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  18414. if (constant != NULL)
  18415. {
  18416. if (!constant->IsNull())
  18417. importStrNum = constant->mInt32;
  18418. }
  18419. else
  18420. {
  18421. importStrNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  18422. }
  18423. if (importStrNum != -1)
  18424. {
  18425. if (!mStringPoolRefs.Contains(importStrNum))
  18426. mStringPoolRefs.Add(importStrNum);
  18427. }
  18428. }
  18429. }
  18430. }
  18431. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  18432. {
  18433. if (mBfIRBuilder->mIgnoreWrites)
  18434. return;
  18435. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  18436. if (!methodInstance->mIRFunction)
  18437. {
  18438. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  18439. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  18440. BF_ASSERT(dllImportGlobalVar || methodInstance->mHasFailed);
  18441. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  18442. }
  18443. if (HasCompiledOutput())
  18444. {
  18445. BfDllImportEntry dllImportEntry;
  18446. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  18447. dllImportEntry.mMethodInstance = mCurMethodInstance;
  18448. mDllImportEntries.push_back(dllImportEntry);
  18449. }
  18450. return;
  18451. }
  18452. auto _SanityCheckType = [&](BfType* type)
  18453. {
  18454. if ((type != NULL) && (type->IsDeleting()))
  18455. {
  18456. InternalError("Method references deleted type", methodDef->GetRefNode());
  18457. return false;
  18458. }
  18459. return true;
  18460. };
  18461. if (!_SanityCheckType(methodInstance->mReturnType))
  18462. return;
  18463. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  18464. if (!_SanityCheckType(methodInstance->GetParamType(paramIdx)))
  18465. return;
  18466. StringT<512> mangledName;
  18467. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  18468. if (!methodInstance->mIRFunction)
  18469. {
  18470. bool isIntrinsic = false;
  18471. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  18472. }
  18473. if (methodInstance->mIsIntrinsic)
  18474. return;
  18475. if (mCurTypeInstance->IsFunction())
  18476. return;
  18477. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  18478. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  18479. if (methodDef->mBody != NULL)
  18480. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18481. else if (methodDeclaration != NULL)
  18482. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18483. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18484. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  18485. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18486. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18487. if ((mCurMethodState == NULL) && (!IsInSpecializedSection())) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  18488. {
  18489. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()))
  18490. {
  18491. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(methodDef->mBody))
  18492. {
  18493. SetAndRestoreValue<bool> prevSkipAnonTypes(sourceClassifier->mSkipAnonymousTypes, true);
  18494. sourceClassifier->VisitChildNoRef(methodDef->mBody);
  18495. }
  18496. }
  18497. }
  18498. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  18499. BfMethodState methodState;
  18500. if (mCurMethodState != NULL)
  18501. methodState.mClosureState = mCurMethodState->mClosureState;
  18502. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  18503. {
  18504. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  18505. if (methodInstance->mHotMethod == NULL)
  18506. CheckHotMethod(methodInstance, mangledName);
  18507. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  18508. }
  18509. methodState.mPrevMethodState = mCurMethodState;
  18510. methodState.mMethodInstance = methodInstance;
  18511. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  18512. if (methodInstance->GetCustomAttributes() != NULL)
  18513. {
  18514. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  18515. if (typeOptionsIdx != -1)
  18516. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  18517. }
  18518. BfTypeState typeState(mCurTypeInstance);
  18519. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  18520. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  18521. BfMethodInstance* unspecializedMethodInstance = NULL;
  18522. if ((prevMethodState.mPrevVal != NULL) &&
  18523. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  18524. {
  18525. // This is 'inner' (probably a closure) - use binding from outer function
  18526. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  18527. }
  18528. else if ((methodInstance->mIsUnspecialized) ||
  18529. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  18530. {
  18531. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  18532. }
  18533. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  18534. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation || mIsComptimeModule) && (!methodInstance->mMethodDef->mIsLocalMethod) && (!methodInstance->mMethodDef->mDeclaringType->IsEmitted()))))
  18535. {
  18536. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  18537. if ((mIsComptimeModule) && (!unspecializedMethodInstance->mHasBeenProcessed))
  18538. {
  18539. // This will have already been populated by CeMachine
  18540. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  18541. }
  18542. else
  18543. {
  18544. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  18545. if (!unspecializedMethodInstance->mHasBeenProcessed)
  18546. {
  18547. // Make sure the unspecialized method is processed so we can take its bindings
  18548. // Clear mCurMethodState so we don't think we're in a local method
  18549. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  18550. if (unspecializedMethodInstance->mMethodProcessRequest == NULL)
  18551. unspecializedMethodInstance->mDeclModule->mIncompleteMethodCount++;
  18552. mContext->ProcessMethod(unspecializedMethodInstance);
  18553. }
  18554. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  18555. }
  18556. }
  18557. if (methodDef->mMethodType == BfMethodType_Operator)
  18558. {
  18559. auto operatorDef = (BfOperatorDef*) methodDef;
  18560. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  18561. auto paramErrorRefNode = refNode;
  18562. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  18563. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  18564. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  18565. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  18566. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  18567. {
  18568. if (methodDef->mParams.size() != 2)
  18569. {
  18570. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  18571. }
  18572. else
  18573. {
  18574. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18575. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18576. checkParam0 = checkParam0->GetUnderlyingType();
  18577. auto checkParam1 = mCurMethodInstance->GetParamType(1);
  18578. if ((checkParam1->IsRef()) && (!checkParam1->IsOut()))
  18579. checkParam1 = checkParam1->GetUnderlyingType();
  18580. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  18581. (checkParam1 != mCurTypeInstance) && (!checkParam1->IsSelf()))
  18582. {
  18583. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  18584. }
  18585. }
  18586. BfType* wantType = NULL;
  18587. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  18588. {
  18589. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  18590. }
  18591. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  18592. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  18593. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  18594. }
  18595. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  18596. {
  18597. if (methodDef->mIsStatic)
  18598. {
  18599. if (methodDef->mParams.size() != 1)
  18600. {
  18601. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  18602. }
  18603. else
  18604. {
  18605. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18606. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18607. checkParam0 = checkParam0->GetUnderlyingType();
  18608. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()))
  18609. {
  18610. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  18611. }
  18612. }
  18613. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  18614. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  18615. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  18616. {
  18617. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  18618. }
  18619. }
  18620. else
  18621. {
  18622. if (methodDef->mParams.size() != 0)
  18623. {
  18624. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  18625. }
  18626. if (!mCurMethodInstance->mReturnType->IsVoid())
  18627. {
  18628. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  18629. }
  18630. }
  18631. }
  18632. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  18633. {
  18634. if (methodDef->mParams.size() != 1)
  18635. {
  18636. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  18637. }
  18638. if (!mCurMethodInstance->mReturnType->IsVoid())
  18639. {
  18640. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  18641. }
  18642. }
  18643. else // Conversion
  18644. {
  18645. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  18646. {
  18647. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  18648. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  18649. }
  18650. if (methodDef->mParams.size() != 1)
  18651. {
  18652. auto refNode = paramErrorRefNode;
  18653. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  18654. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  18655. Fail("Conversion operators must declare one parameter", refNode);
  18656. }
  18657. else if ((methodInstance->mMethodInfoEx == NULL) ||
  18658. (methodInstance->mMethodInfoEx->mMethodGenericArguments.IsEmpty()) ||
  18659. ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation)))
  18660. {
  18661. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18662. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18663. checkParam0 = checkParam0->GetUnderlyingType();
  18664. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  18665. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  18666. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  18667. if (checkParam0 == mCurMethodInstance->mReturnType)
  18668. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  18669. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  18670. // happened here
  18671. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (checkParam0 != mContext->mBfObjectType)))
  18672. {
  18673. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  18674. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, checkParam0->ToTypeInstance());
  18675. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  18676. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  18677. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  18678. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  18679. }
  18680. }
  18681. }
  18682. }
  18683. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mBfIRBuilder->mIgnoreWrites) && (mHasFullDebugInfo);
  18684. if (methodDef->mMethodType == BfMethodType_Mixin)
  18685. wantsDIData = false;
  18686. if (mCurTypeInstance->IsUnspecializedType())
  18687. wantsDIData = false;
  18688. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  18689. wantsDIData = false;
  18690. bool wantsDIVariables = wantsDIData;
  18691. if (methodDef->mIsExtern)
  18692. wantsDIVariables = false;
  18693. SizedArray<BfIRMDNode, 8> diParams;
  18694. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  18695. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  18696. BfType* thisType = NULL;
  18697. if (!methodDef->mIsStatic)
  18698. {
  18699. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  18700. thisType = methodState.mClosureState->mClosureType;
  18701. else
  18702. thisType = mCurTypeInstance;
  18703. }
  18704. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  18705. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  18706. //////////////////////////////////////////////////////////////////////////
  18707. //
  18708. {
  18709. if (methodDeclaration != NULL)
  18710. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18711. else if (methodDef->mBody != NULL)
  18712. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18713. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18714. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  18715. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18716. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18717. }
  18718. BfIRMDNode diFunction;
  18719. if (wantsDIData)
  18720. {
  18721. BP_ZONE("BfModule::DoMethodDeclaration.DISetup");
  18722. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  18723. int defLine = mCurFilePosition.mCurLine;
  18724. if (mDICompileUnit)
  18725. {
  18726. // Note: for comptime we need to ensure we don't force type population with DbgGetTypeInst here, as that
  18727. // can generate a CeMachine InitType circular data reference
  18728. int flags = 0;
  18729. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance, BfIRPopulateType_Identity);
  18730. if (methodDef->mProtection == BfProtection_Public)
  18731. flags = llvm::DINode::FlagPublic;
  18732. else if (methodDef->mProtection == BfProtection_Protected)
  18733. flags = llvm::DINode::FlagProtected;
  18734. else
  18735. flags = llvm::DINode::FlagPrivate;
  18736. if (methodDef->mIsOverride)
  18737. {
  18738. //flags |= llvm::DINode::FlagVirtual;
  18739. }
  18740. else if (methodDef->mIsVirtual)
  18741. flags |= llvm::DINode::FlagIntroducedVirtual;
  18742. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  18743. flags |= llvm::DINode::FlagStaticMember;
  18744. else
  18745. {
  18746. if ((mCurTypeInstance->IsValuelessType()) ||
  18747. ((!mIsComptimeModule) && (mCurTypeInstance->IsSplattable())))
  18748. flags |= llvm::DINode::FlagStaticMember;
  18749. }
  18750. flags |= llvm::DINode::FlagPrototyped;
  18751. if (methodDef->mMethodType == BfMethodType_Ctor)
  18752. {
  18753. flags |= llvm::DINode::FlagArtificial;
  18754. }
  18755. auto llvmFunction = methodInstance->mIRFunction;
  18756. SizedArray<BfIRMDNode, 1> genericArgs;
  18757. SizedArray<BfIRValue, 1> genericConstValueArgs;
  18758. String methodName;
  18759. if (methodInstance->GetForeignType() != NULL)
  18760. {
  18761. methodName += TypeToString(methodInstance->GetForeignType());
  18762. methodName += ".";
  18763. }
  18764. if (methodInstance->GetExplicitInterface() != NULL)
  18765. {
  18766. methodName += TypeToString(methodInstance->GetExplicitInterface());
  18767. methodName += ".";
  18768. }
  18769. methodName += methodDef->mName;
  18770. if (methodInstance->GetNumGenericArguments() != 0)
  18771. {
  18772. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  18773. {
  18774. if (genericArg->IsConstExprValue())
  18775. {
  18776. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  18777. while (genericConstValueArgs.size() < genericArgs.size())
  18778. genericConstValueArgs.push_back(BfIRValue());
  18779. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  18780. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  18781. }
  18782. else
  18783. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  18784. }
  18785. methodName += "<";
  18786. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  18787. {
  18788. if (i > 0)
  18789. methodName += ", ";
  18790. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  18791. methodName += TypeToString(type);
  18792. }
  18793. methodName += ">";
  18794. }
  18795. if ((methodName.empty()) && (methodDeclaration != NULL))
  18796. {
  18797. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18798. {
  18799. methodName += "operator";
  18800. if (operatorDecl->mIsConvOperator)
  18801. {
  18802. methodName += " ";
  18803. methodName += TypeToString(methodInstance->mReturnType);
  18804. }
  18805. else if (operatorDecl->mOpTypeToken != NULL)
  18806. methodName += operatorDecl->mOpTypeToken->ToString();
  18807. }
  18808. }
  18809. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  18810. methodName += "$CHK";
  18811. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  18812. methodName += "$UCHK";
  18813. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18814. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18815. // defLine + 1, diFuncType, false, true,
  18816. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  18817. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  18818. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18819. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18820. defLine + 1, diFuncType, false, true,
  18821. llvm::dwarf::DW_VIRTUALITY_none,
  18822. 0,
  18823. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18824. }
  18825. else
  18826. {
  18827. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18828. }
  18829. }
  18830. //////////////////////////////////////////////////////////////////////////
  18831. // Head and Init get rolled into Entry afterwards.
  18832. methodState.mIRFunction = methodInstance->mIRFunction;
  18833. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  18834. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  18835. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  18836. methodState.mCurScope->mDIScope = diFunction;
  18837. auto llvmEntryBlock = methodState.mIREntryBlock;
  18838. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  18839. if (methodDef->mName == "__MALFORMED")
  18840. {
  18841. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  18842. mBfIRBuilder->SetInsertPoint(newBlock);
  18843. }
  18844. if (methodDef->mBody != NULL)
  18845. {
  18846. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18847. }
  18848. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  18849. {
  18850. // We want to be able to step into delegate invokes -- we actually step over them
  18851. if (methodDef->mName != "Invoke")
  18852. {
  18853. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18854. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  18855. }
  18856. }
  18857. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18858. mBfIRBuilder->ClearDebugLocation();
  18859. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  18860. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  18861. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  18862. {
  18863. int localIdx = 0;
  18864. int argIdx = 0;
  18865. Array<BfIRValue> splatAddrValues;
  18866. for ( ; argIdx < irParamCount; localIdx++)
  18867. {
  18868. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18869. if ((isThis) && (thisType->IsValuelessNonOpaqueType()))
  18870. isThis = false;
  18871. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() == argIdx))
  18872. {
  18873. argIdx++;
  18874. if (argIdx == irParamCount)
  18875. break;
  18876. }
  18877. BfLocalVariable* paramVar = NULL;
  18878. while (true)
  18879. {
  18880. if (localIdx >= methodState.mLocals.size())
  18881. {
  18882. paramVar = NULL;
  18883. break;
  18884. }
  18885. paramVar = methodState.mLocals[localIdx];
  18886. if ((paramVar->mCompositeCount == -1) &&
  18887. (!paramVar->mIsConst) &&
  18888. ((!paramVar->mResolvedType->IsValuelessNonOpaqueType()) || (paramVar->mResolvedType->IsMethodRef())))
  18889. break;
  18890. localIdx++;
  18891. }
  18892. if (paramVar == NULL)
  18893. {
  18894. Fail("Parameter count error", methodDef->GetRefNode());
  18895. break;
  18896. }
  18897. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  18898. {
  18899. paramVar->mIsReadOnly = true;
  18900. }
  18901. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) ||
  18902. ((!mIsComptimeModule) && (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter)));
  18903. if (paramVar->mResolvedType->IsMethodRef())
  18904. wantsAddr = false;
  18905. // if ((methodDef->mHasAppend) && (argIdx == 1))
  18906. // {
  18907. // BF_ASSERT(paramVar->mName == "appendIdx");
  18908. // wantsAddr = true;
  18909. // }
  18910. if (paramVar->mIsSplat)
  18911. {
  18912. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18913. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18914. BfTypeUtils::SplatIterate([&](BfType* checkType)
  18915. {
  18916. BfIRType splatIRType;
  18917. if (checkType->IsComposite())
  18918. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  18919. else
  18920. splatIRType = mBfIRBuilder->MapType(checkType);
  18921. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  18922. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  18923. if (!paramVar->mAddr)
  18924. paramVar->mAddr = allocaInst;
  18925. if (WantsLifetimes())
  18926. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18927. splatAddrValues.push_back(allocaInst);
  18928. }, paramVar->mResolvedType);
  18929. mBfIRBuilder->SetInsertPoint(prevInsert);
  18930. }
  18931. else if (isThis)
  18932. {
  18933. if (wantsAddr)
  18934. {
  18935. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18936. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18937. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  18938. if (paramVar->mIsSplat)
  18939. {
  18940. //
  18941. }
  18942. else
  18943. {
  18944. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  18945. if ((thisType->IsTypedPrimitive()) &&
  18946. ((methodDef->HasNoThisSplat()) || (methodInstance->ForcingThisPtr())))
  18947. wantPtr = true;
  18948. if (wantPtr)
  18949. {
  18950. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  18951. }
  18952. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  18953. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18954. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  18955. paramVar->mAddr = allocaInst;
  18956. if (WantsLifetimes())
  18957. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18958. }
  18959. mBfIRBuilder->SetInsertPoint(prevInsert);
  18960. }
  18961. }
  18962. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  18963. {
  18964. // Address doesn't change so we don't have to alloca it
  18965. BfIRType allocType;
  18966. int alignSize = mSystem->mPtrSize;
  18967. if (paramVar->mResolvedType->IsRef())
  18968. {
  18969. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18970. }
  18971. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  18972. {
  18973. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18974. alignSize = paramVar->mResolvedType->mAlign;
  18975. }
  18976. else
  18977. {
  18978. paramVar->mHasLocalStructBacking = true;
  18979. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  18980. if (typeInst != NULL)
  18981. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  18982. else
  18983. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  18984. }
  18985. if (wantsAddr)
  18986. {
  18987. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18988. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18989. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18990. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  18991. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18992. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  18993. paramVar->mAddr = allocaInst;
  18994. mBfIRBuilder->SetInsertPoint(prevInsert);
  18995. if (WantsLifetimes())
  18996. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18997. }
  18998. }
  18999. else if (wantsAddr)
  19000. {
  19001. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  19002. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  19003. paramVar->mAddr = allocaInst;
  19004. }
  19005. if (paramVar->mIsSplat)
  19006. {
  19007. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  19008. }
  19009. else if (paramVar->mIsLowered)
  19010. {
  19011. BfTypeCode loweredTypeCode = BfTypeCode_None;
  19012. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  19013. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  19014. argIdx++;
  19015. if (loweredTypeCode2 != BfTypeCode_None)
  19016. argIdx++;
  19017. }
  19018. else
  19019. {
  19020. argIdx++;
  19021. }
  19022. }
  19023. if (methodDef->mBody != NULL)
  19024. UpdateSrcPos(methodDef->mBody);
  19025. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  19026. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  19027. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  19028. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  19029. localIdx = 0;
  19030. argIdx = 0;
  19031. int splatAddrIdx = 0;
  19032. while (localIdx < (int)methodState.mLocals.size())
  19033. {
  19034. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  19035. argIdx++;
  19036. int curLocalIdx = localIdx++;
  19037. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  19038. if (paramVar->mIsConst)
  19039. continue;
  19040. if (!paramVar->IsParam())
  19041. continue;
  19042. if (paramVar->mCompositeCount != -1)
  19043. continue;
  19044. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  19045. if ((isThis) && (thisType->IsValuelessNonOpaqueType()))
  19046. isThis = false;
  19047. if (paramVar->mValue.IsArg())
  19048. BF_ASSERT(paramVar->mValue.mId == argIdx);
  19049. BfIRMDNode diVariable;
  19050. if (wantsDIData)
  19051. {
  19052. String paramName = paramVar->mName;
  19053. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  19054. if (isThis)
  19055. {
  19056. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  19057. paramName = "__closure";
  19058. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  19059. {
  19060. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  19061. bool wantRef = paramVar->mResolvedType->IsComposite();
  19062. if ((paramVar->mResolvedType->IsTypedPrimitive()) &&
  19063. ((methodDef->HasNoThisSplat()) || (methodInstance->ForcingThisPtr())))
  19064. wantRef = true;
  19065. if (wantRef)
  19066. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  19067. }
  19068. else if (!paramVar->mResolvedType->IsValueType())
  19069. {
  19070. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  19071. }
  19072. }
  19073. else
  19074. {
  19075. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  19076. {
  19077. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  19078. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  19079. diType = mBfIRBuilder->DbgCreateConstType(diType);
  19080. }
  19081. }
  19082. if (!paramVar->mIsSplat)
  19083. {
  19084. if ((paramVar->mParamIdx >= 0) && (paramVar->mParamIdx < methodInstance->mDefaultValues.mSize))
  19085. {
  19086. auto defaultValue = methodInstance->mDefaultValues[paramVar->mParamIdx];
  19087. auto constant = mCurTypeInstance->mConstHolder->GetConstant(defaultValue.mValue);
  19088. if ((constant != NULL) &&
  19089. ((BfIRConstHolder::IsIntable(constant->mTypeCode)) || (BfIRConstHolder::IsFloat(constant->mTypeCode))))
  19090. {
  19091. int64 writeVal = constant->mInt64;
  19092. if (constant->mTypeCode == BfTypeCode_Float)
  19093. {
  19094. // We need to do this because Singles are stored in mDouble, so we need to reduce here
  19095. float floatVal = (float)constant->mDouble;
  19096. writeVal = *(uint32*)&floatVal;
  19097. }
  19098. if (writeVal < 0)
  19099. paramName += StrFormat("$_%llu", -writeVal);
  19100. else
  19101. paramName += StrFormat("$%llu", writeVal);
  19102. }
  19103. }
  19104. if (paramVar->mResolvedType->IsValuelessNonOpaqueType())
  19105. {
  19106. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  19107. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  19108. }
  19109. else if (paramVar->mIsImplicitParam)
  19110. {
  19111. // Annotate this specially?
  19112. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  19113. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  19114. }
  19115. else
  19116. {
  19117. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  19118. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  19119. }
  19120. paramVar->mDbgVarInst = diVariable;
  19121. }
  19122. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  19123. {
  19124. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  19125. // {
  19126. // // Only add this placeholder if we don't have any values
  19127. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  19128. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  19129. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  19130. // }
  19131. }
  19132. }
  19133. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  19134. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  19135. {
  19136. // Write our argument value into the .addr
  19137. mBfIRBuilder->ClearDebugLocation();
  19138. if (paramVar->mIsSplat)
  19139. {
  19140. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  19141. //
  19142. }
  19143. else
  19144. {
  19145. bool handled = false;
  19146. if (paramVar->mIsLowered)
  19147. {
  19148. BfTypeCode loweredTypeCode = BfTypeCode_None;
  19149. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  19150. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  19151. {
  19152. BfIRValue targetAddr = paramVar->mAddr;
  19153. bool isTempTarget = false;
  19154. int loweredSize = mBfIRBuilder->GetSize(loweredTypeCode) + mBfIRBuilder->GetSize(loweredTypeCode2);
  19155. if (paramVar->mResolvedType->mSize < loweredSize)
  19156. {
  19157. isTempTarget = true;
  19158. targetAddr = CreateAlloca(GetPrimitiveType(BfTypeCode_Int8), true, NULL, GetConstValue(loweredSize));
  19159. mBfIRBuilder->SetAllocaAlignment(targetAddr,
  19160. BF_MAX(paramVar->mResolvedType->mAlign,
  19161. BF_MAX(mBfIRBuilder->GetSize(loweredTypeCode), mBfIRBuilder->GetSize(loweredTypeCode2))));
  19162. }
  19163. // We have a lowered type coming in, so we have to cast the .addr before storing
  19164. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  19165. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  19166. auto primPtrVal = mBfIRBuilder->CreateBitCast(targetAddr, primPtrType);
  19167. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, mCurTypeInstance->mAlign);
  19168. if (loweredTypeCode2 != BfTypeCode_None)
  19169. {
  19170. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  19171. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  19172. BfIRValue primPtrVal2;
  19173. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  19174. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  19175. else
  19176. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  19177. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  19178. }
  19179. if (isTempTarget)
  19180. {
  19181. auto castedTempPtr = mBfIRBuilder->CreateBitCast(targetAddr, mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType)));
  19182. auto tempVal = mBfIRBuilder->CreateAlignedLoad(castedTempPtr, paramVar->mResolvedType->mAlign);
  19183. mBfIRBuilder->CreateAlignedStore(tempVal, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  19184. }
  19185. // We don't want to allow directly using value
  19186. paramVar->mValue = BfIRValue();
  19187. handled = true;
  19188. }
  19189. else
  19190. {
  19191. BF_ASSERT("Expected lowered");
  19192. }
  19193. }
  19194. if (!handled)
  19195. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  19196. }
  19197. }
  19198. if (methodDef->mBody != NULL)
  19199. UpdateSrcPos(methodDef->mBody);
  19200. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  19201. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  19202. else if (methodDeclaration == NULL)
  19203. UseDefaultSrcPos();
  19204. // Write our argument value into the .addr
  19205. if (paramVar->mIsSplat)
  19206. {
  19207. int splatComponentIdx = 0;
  19208. auto curArgIdx = argIdx;
  19209. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  19210. {
  19211. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  19212. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  19213. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  19214. mBfIRBuilder->ClearDebugLocation(storeInst);
  19215. if (wantsDIData)
  19216. {
  19217. BfIRMDNode diType;
  19218. if (checkType->IsComposite())
  19219. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  19220. else
  19221. diType = mBfIRBuilder->DbgGetType(checkType);
  19222. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  19223. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  19224. if (wantsDIVariables)
  19225. {
  19226. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  19227. }
  19228. }
  19229. curArgIdx++;
  19230. splatComponentIdx++;
  19231. };
  19232. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  19233. {
  19234. if (checkType->IsStruct())
  19235. {
  19236. auto checkTypeInstance = checkType->ToTypeInstance();
  19237. if (checkTypeInstance->mBaseType != NULL)
  19238. {
  19239. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  19240. }
  19241. if (checkTypeInstance->mIsUnion)
  19242. {
  19243. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  19244. if (!unionInnerType->IsValuelessType())
  19245. {
  19246. _FinishSplatsIterate(unionInnerType, name + "$u");
  19247. }
  19248. if (checkTypeInstance->IsEnum())
  19249. {
  19250. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  19251. _FinishSplatsIterate(dscrType, name + "$d");
  19252. }
  19253. }
  19254. else
  19255. {
  19256. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  19257. {
  19258. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  19259. auto fieldDef = fieldInstance->GetFieldDef();
  19260. if (fieldInstance->mDataIdx >= 0)
  19261. {
  19262. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  19263. }
  19264. }
  19265. }
  19266. }
  19267. else if (checkType->IsMethodRef())
  19268. {
  19269. auto methodRefType = (BfMethodRefType*)checkType;
  19270. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  19271. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  19272. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  19273. // {
  19274. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  19275. // if (!paramType->IsValuelessType())
  19276. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  19277. // }
  19278. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  19279. {
  19280. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  19281. String paramName = methodInstance->GetParamName(paramIdx);
  19282. if (paramName == "this")
  19283. paramName = "__this";
  19284. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  19285. {
  19286. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  19287. }
  19288. else
  19289. {
  19290. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  19291. }
  19292. }
  19293. }
  19294. else if (!checkType->IsValuelessType())
  19295. {
  19296. _FinishSplats(checkType, name);
  19297. }
  19298. };
  19299. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  19300. if (!paramVar->mConstValue)
  19301. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  19302. }
  19303. BfIRValue declareCall;
  19304. if (diVariable)
  19305. {
  19306. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  19307. {
  19308. if (!paramVar->mAddr)
  19309. {
  19310. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  19311. {
  19312. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  19313. {
  19314. // We don't need to set the location for this
  19315. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  19316. }
  19317. }
  19318. else
  19319. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  19320. }
  19321. else
  19322. {
  19323. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  19324. }
  19325. }
  19326. }
  19327. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  19328. {
  19329. // We don't allow actually assignment to "this", so we just do a single load
  19330. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  19331. // we need to store it in the stack frame for debugging purposes
  19332. auto loadedThis = mBfIRBuilder->CreateAlignedLoad(paramVar->mAddr/*, "this"*/, paramVar->mResolvedType->mAlign);
  19333. mBfIRBuilder->ClearDebugLocation(loadedThis);
  19334. paramVar->mValue = loadedThis;
  19335. }
  19336. if ((wantsDIData) && (declareCall))
  19337. mBfIRBuilder->UpdateDebugLocation(declareCall);
  19338. if (paramVar->mIsSplat)
  19339. {
  19340. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  19341. }
  19342. else if (paramVar->mIsLowered)
  19343. {
  19344. argIdx++;
  19345. BfTypeCode loweredTypeCode = BfTypeCode_None;
  19346. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  19347. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  19348. if (loweredTypeCode2 != BfTypeCode_None)
  19349. argIdx++;
  19350. }
  19351. else if ((isThis) && (paramVar->mResolvedType->IsOpaque()))
  19352. {
  19353. if ((methodDef->mIsMutating) || (methodInstance->ForcingThisPtr()))
  19354. argIdx++;
  19355. }
  19356. else if (!paramVar->mResolvedType->IsValuelessNonOpaqueType())
  19357. {
  19358. argIdx++;
  19359. }
  19360. }
  19361. if (wantsDIData)
  19362. {
  19363. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  19364. }
  19365. }
  19366. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  19367. {
  19368. auto paramVar = mCurMethodState->mLocals[varIdx];
  19369. // 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
  19370. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  19371. // if (paramVar->mIsSplat)
  19372. // {
  19373. // if (wantsDIVariables)
  19374. // {
  19375. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  19376. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  19377. // }
  19378. // }
  19379. if (paramVar->mResolvedType->IsValuelessType())
  19380. {
  19381. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  19382. {
  19383. // Only add this placeholder if we don't have any values
  19384. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  19385. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  19386. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  19387. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  19388. }
  19389. }
  19390. }
  19391. if (IsTargetingBeefBackend())
  19392. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  19393. if (methodState.mClosureState != NULL)
  19394. {
  19395. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  19396. {
  19397. BfLocalVariable* localVar = new BfLocalVariable();
  19398. *localVar = constLocal;
  19399. localVar->mIsBumpAlloc = false;
  19400. AddLocalVariableDef(localVar, true);
  19401. }
  19402. }
  19403. bool wantsRemoveBody = false;
  19404. bool skipBody = false;
  19405. bool skipUpdateSrcPos = false;
  19406. bool skipEndChecks = false;
  19407. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  19408. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  19409. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  19410. hasExternSpecifier = true;
  19411. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  19412. {
  19413. // We need to be able to mark deleted objects
  19414. mCurMethodState->mIgnoreObjectAccessCheck = true;
  19415. }
  19416. auto customAttributes = methodInstance->GetCustomAttributes();
  19417. if (customAttributes != NULL)
  19418. {
  19419. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  19420. mCurMethodState->mIgnoreObjectAccessCheck = true;
  19421. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  19422. mCurMethodState->mDisableChecks = true;
  19423. }
  19424. // Allocate, clear, set classVData
  19425. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  19426. {
  19427. CreateStaticCtor();
  19428. }
  19429. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  19430. {
  19431. skipBody = true;
  19432. skipEndChecks = true;
  19433. if (HasExecutedOutput())
  19434. {
  19435. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  19436. mBfIRBuilder->ClearDebugLocation();
  19437. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  19438. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  19439. PopulateType(innerType, BfPopulateType_DataAndMethods);
  19440. mBfIRBuilder->PopulateType(mCurTypeInstance);
  19441. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  19442. if (methodInstance->mIsForeignMethodDef)
  19443. {
  19444. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  19445. }
  19446. BfTypeVector methodGenericArguments;
  19447. if (methodInstance->mMethodInfoEx != NULL)
  19448. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  19449. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  19450. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  19451. {
  19452. if (!methodInstance->mReturnType->IsValuelessType())
  19453. {
  19454. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  19455. CreateReturn(retVal);
  19456. }
  19457. else
  19458. mBfIRBuilder->CreateRetVoid();
  19459. }
  19460. else
  19461. {
  19462. auto innerMethodDef = innerMethodInstance.mMethodInstance->mMethodDef;
  19463. if ((innerMethodDef == methodDef != NULL) && (!CompareMethodSignatures(methodInstance, innerMethodInstance.mMethodInstance)))
  19464. {
  19465. InternalError("Boxing method passthrough error");
  19466. }
  19467. else
  19468. {
  19469. SizedArray<BfIRValue, 8> innerParams;
  19470. BfExprEvaluator exprEvaluator(this);
  19471. if (!innerType->IsValuelessType())
  19472. {
  19473. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  19474. BfTypedValue innerVal(thisValue, innerType, true);
  19475. if (boxedType->IsBoxedStructPtr())
  19476. {
  19477. innerVal = LoadValue(innerVal);
  19478. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  19479. }
  19480. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  19481. }
  19482. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  19483. {
  19484. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  19485. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  19486. exprEvaluator.PushArg(localVal, innerParams);
  19487. }
  19488. if (!innerMethodInstance.mFunc)
  19489. {
  19490. BF_ASSERT(innerType->IsUnspecializedType());
  19491. }
  19492. else if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  19493. {
  19494. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  19495. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  19496. exprEvaluator.mReceivingValue = &returnType;
  19497. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  19498. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  19499. mBfIRBuilder->CreateRetVoid();
  19500. }
  19501. else
  19502. {
  19503. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  19504. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  19505. if (mCurMethodInstance->mReturnType->IsValueType())
  19506. retVal = LoadValue(retVal);
  19507. CreateReturn(retVal.mValue);
  19508. }
  19509. }
  19510. }
  19511. }
  19512. mCurMethodState->SetHadReturn(true);
  19513. mCurMethodState->mLeftBlockUncond = true;
  19514. }
  19515. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  19516. {
  19517. SetIllegalSrcPos();
  19518. mBfIRBuilder->ClearDebugLocation();
  19519. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  19520. auto thisVal = GetThis();
  19521. int prevSize = 0;
  19522. if ((mContext->mBfObjectType != NULL) && (mCurTypeInstance->IsObject()))
  19523. {
  19524. prevSize = mContext->mBfObjectType->mInstSize;
  19525. PopulateType(mContext->mBfObjectType);
  19526. // If we have object extensions, clear out starting at the extension
  19527. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  19528. {
  19529. if (fieldInstance.GetFieldDef()->mDeclaringType->IsExtension())
  19530. {
  19531. prevSize = fieldInstance.mDataOffset;
  19532. break;
  19533. }
  19534. }
  19535. }
  19536. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  19537. int curSize = mCurTypeInstance->mInstSize;
  19538. if (curSize > prevSize)
  19539. {
  19540. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  19541. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  19542. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  19543. }
  19544. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  19545. {
  19546. auto useThis = mCurMethodState->mLocals[0]->mValue;
  19547. auto useThisType = mCurTypeInstance;
  19548. auto checkTypeInst = mCurTypeInstance;
  19549. while (checkTypeInst != NULL)
  19550. {
  19551. for (auto& fieldInstance : checkTypeInst->mFieldInstances)
  19552. {
  19553. auto fieldDef = fieldInstance.GetFieldDef();
  19554. if ((fieldDef == NULL) || (fieldDef->mIsStatic))
  19555. continue;
  19556. if (fieldInstance.IsAppendedObject())
  19557. {
  19558. if (checkTypeInst != useThisType)
  19559. {
  19560. useThis = mBfIRBuilder->CreateBitCast(useThis, mBfIRBuilder->MapType(checkTypeInst));
  19561. useThisType = checkTypeInst;
  19562. }
  19563. BfIRValue fieldAddr = mBfIRBuilder->CreateInBoundsGEP(useThis, 0, fieldInstance.mDataIdx);
  19564. auto int8PtrVal = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(int8PtrType));
  19565. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  19566. }
  19567. }
  19568. checkTypeInst = checkTypeInst->mBaseType;
  19569. }
  19570. }
  19571. skipUpdateSrcPos = true;
  19572. }
  19573. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  19574. {
  19575. EmitCtorBody(skipBody);
  19576. }
  19577. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  19578. {
  19579. EmitDtorBody();
  19580. skipBody = true;
  19581. }
  19582. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  19583. {
  19584. EmitIteratorBlock(skipBody);
  19585. }
  19586. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  19587. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  19588. {
  19589. // We chain even non-default ctors to the default ctors
  19590. auto defaultCtor = methodInstance;
  19591. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  19592. CallChainedMethods(defaultCtor, false);
  19593. }
  19594. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  19595. if (!mCompiler->mHasRequiredTypes)
  19596. {
  19597. // Skip processing to avoid errors
  19598. }
  19599. else if (methodDef->mBody == NULL)
  19600. {
  19601. if (methodDeclaration != NULL)
  19602. {
  19603. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  19604. {
  19605. if (operatorDeclaration->mIsConvOperator)
  19606. wantsRemoveBody = true;
  19607. }
  19608. }
  19609. bool isDllImport = false;
  19610. if ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic))
  19611. {
  19612. if (importStrNum != -1)
  19613. {
  19614. if (importKind == BfImportKind_Import_Static)
  19615. {
  19616. if (!mImportFileNames.Contains(importStrNum))
  19617. {
  19618. mImportFileNames.Add(importStrNum);
  19619. }
  19620. }
  19621. }
  19622. }
  19623. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  19624. {
  19625. CreateDllImportMethod();
  19626. }
  19627. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  19628. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  19629. {
  19630. if (mCurTypeInstance->mTypeDef->mIsFunction)
  19631. {
  19632. // Emit nothing
  19633. }
  19634. else
  19635. {
  19636. CreateDelegateInvokeMethod();
  19637. mCurMethodState->SetHadReturn(true);
  19638. mCurMethodState->mLeftBlockUncond = true;
  19639. }
  19640. }
  19641. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_SIGNATURE))
  19642. {
  19643. if (mCurTypeInstance->IsObject())
  19644. {
  19645. CreateDynamicCastMethod();
  19646. }
  19647. else
  19648. {
  19649. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  19650. mCurMethodState->mHadReturn = true;
  19651. }
  19652. }
  19653. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  19654. {
  19655. BfIRValue ret;
  19656. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  19657. {
  19658. // This can happen if we provide an invalid name
  19659. AssertErrorState();
  19660. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  19661. }
  19662. else
  19663. {
  19664. // Unfortunate DebugLoc shenanigans-
  19665. // 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,
  19666. // so we only set the loc on the CreateRet which gets inlined out
  19667. mBfIRBuilder->SaveDebugLocation();
  19668. mBfIRBuilder->ClearDebugLocation();
  19669. BfIRValue fromBool;
  19670. if ((!mCurTypeInstance->IsTypedPrimitive()) || (mCurTypeInstance->IsValuelessType()))
  19671. {
  19672. fromBool = GetDefaultValue(methodInstance->mReturnType);
  19673. }
  19674. else
  19675. {
  19676. BfIRValue thisValue = LoadValue(GetThis()).mValue;
  19677. auto andResult = mBfIRBuilder->CreateAnd(thisValue, mCurMethodState->mLocals[1]->mValue);
  19678. auto toBool = mBfIRBuilder->CreateCmpEQ(andResult, mCurMethodState->mLocals[1]->mValue);
  19679. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  19680. }
  19681. mBfIRBuilder->RestoreDebugLocation();
  19682. ret = mBfIRBuilder->CreateRet(fromBool);
  19683. //ExtendLocalLifetimes(0);
  19684. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19685. }
  19686. mCurMethodState->SetHadReturn(true);
  19687. mCurMethodState->mLeftBlockUncond = true;
  19688. }
  19689. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  19690. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  19691. {
  19692. BfIRValue ret;
  19693. // Unfortunate DebugLoc shenanigans-
  19694. // 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,
  19695. // so we only set the loc on the CreateRet which gets inlined out
  19696. mBfIRBuilder->SaveDebugLocation();
  19697. mBfIRBuilder->ClearDebugLocation();
  19698. BfIRValue fromBool;
  19699. mBfIRBuilder->RestoreDebugLocation();
  19700. if ((!mCompiler->mIsResolveOnly) || (mIsComptimeModule))
  19701. {
  19702. if (!mCurTypeInstance->IsValuelessType())
  19703. {
  19704. auto thisValueOrAddr = GetThis();
  19705. BfIRValue thisValue;
  19706. if (!methodInstance->mReturnType->IsRef())
  19707. thisValue = LoadValue(thisValueOrAddr).mValue;
  19708. else
  19709. thisValue = thisValueOrAddr.mValue;
  19710. ret = mBfIRBuilder->CreateRet(thisValue);
  19711. }
  19712. else
  19713. mBfIRBuilder->CreateRetVoid();
  19714. }
  19715. //ExtendLocalLifetimes(0);
  19716. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19717. mCurMethodState->SetHadReturn(true);
  19718. mCurMethodState->mLeftBlockUncond = true;
  19719. }
  19720. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  19721. {
  19722. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  19723. if (HasExecutedOutput())
  19724. {
  19725. EmitEnumToStringBody();
  19726. }
  19727. mBfIRBuilder->CreateRetVoid();
  19728. mCurMethodState->SetHadReturn(true);
  19729. mCurMethodState->mLeftBlockUncond = true;
  19730. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19731. }
  19732. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  19733. {
  19734. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  19735. if (HasExecutedOutput())
  19736. {
  19737. EmitTupleToStringBody();
  19738. }
  19739. mBfIRBuilder->CreateRetVoid();
  19740. mCurMethodState->SetHadReturn(true);
  19741. mCurMethodState->mLeftBlockUncond = true;
  19742. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19743. }
  19744. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  19745. {
  19746. CreateValueTypeEqualsMethod(false);
  19747. skipBody = true;
  19748. skipEndChecks = true;
  19749. }
  19750. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  19751. {
  19752. CreateValueTypeEqualsMethod(true);
  19753. skipBody = true;
  19754. skipEndChecks = true;
  19755. }
  19756. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef->GetDefinition() == mCompiler->mValueTypeTypeDef))
  19757. {
  19758. CreateValueTypeEqualsMethod(false);
  19759. skipBody = true;
  19760. skipEndChecks = true;
  19761. }
  19762. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (mCurTypeInstance->IsDelegate()))
  19763. {
  19764. CreateDelegateEqualsMethod();
  19765. skipBody = true;
  19766. skipEndChecks = true;
  19767. }
  19768. else
  19769. {
  19770. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  19771. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  19772. {
  19773. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  19774. Fail("Body expected", methodDef->GetRefNode());
  19775. }
  19776. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  19777. {
  19778. if ((methodInstance->mReturnType->IsRef()) && (!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  19779. Fail("Auto-implemented ref property getters must declare 'mut'", methodInstance->mMethodDef->GetRefNode());
  19780. if (methodInstance->mReturnType->IsValuelessType())
  19781. {
  19782. mBfIRBuilder->CreateRetVoid();
  19783. }
  19784. else if (HasExecutedOutput())
  19785. {
  19786. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19787. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19788. BfFieldDef* fieldDef = NULL;
  19789. if (fieldInstance != NULL)
  19790. fieldDef = fieldInstance->GetFieldDef();
  19791. BfType* retType = methodInstance->mReturnType;
  19792. if (retType->IsRef())
  19793. retType = retType->GetUnderlyingType();
  19794. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  19795. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19796. {
  19797. BfTypedValue lookupValue;
  19798. if (fieldDef->IsNonConstStatic())
  19799. lookupValue = ReferenceStaticField(fieldInstance);
  19800. else if (mCurTypeInstance->IsObject())
  19801. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  19802. else
  19803. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  19804. if (methodInstance->mReturnType->IsRef())
  19805. {
  19806. if ((!lookupValue.IsAddr()) && (!lookupValue.mType->IsValuelessType()))
  19807. lookupValue = MakeAddressable(lookupValue);
  19808. }
  19809. else
  19810. lookupValue = LoadOrAggregateValue(lookupValue);
  19811. CreateReturn(lookupValue.mValue);
  19812. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19813. }
  19814. else
  19815. {
  19816. // This can happen if we have two properties with the same name but different types
  19817. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19818. EmitDefaultReturn();
  19819. }
  19820. }
  19821. else
  19822. {
  19823. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19824. EmitDefaultReturn();
  19825. }
  19826. mCurMethodState->SetHadReturn(true);
  19827. }
  19828. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  19829. {
  19830. if ((!methodDef->mIsMutating) && (!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  19831. {
  19832. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  19833. }
  19834. else if (!mCompiler->IsAutocomplete())
  19835. {
  19836. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19837. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19838. auto fieldDef = fieldInstance->GetFieldDef();
  19839. auto& lastParam = mCurMethodState->mLocals.back();
  19840. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  19841. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19842. {
  19843. BfIRValue lookupAddr;
  19844. if (fieldDef->IsNonConstStatic())
  19845. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  19846. else
  19847. {
  19848. auto thisValue = GetThis();
  19849. if (thisValue.IsSplat())
  19850. {
  19851. BFMODULE_FATAL(this, "Should not happen");
  19852. }
  19853. if (mCurTypeInstance->IsObject())
  19854. thisValue = LoadValue(thisValue);
  19855. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  19856. }
  19857. BfExprEvaluator exprEvaluator(this);
  19858. auto localVal = exprEvaluator.LoadLocal(lastParam);
  19859. localVal = LoadOrAggregateValue(localVal);
  19860. if (!localVal.mType->IsValuelessType())
  19861. mBfIRBuilder->CreateAlignedStore(localVal.mValue, lookupAddr, localVal.mType->mAlign);
  19862. }
  19863. else if (!fieldInstance->mResolvedType->IsValuelessType())
  19864. {
  19865. // This can happen if we have two properties with the same name but different types
  19866. AssertErrorState();
  19867. }
  19868. }
  19869. }
  19870. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  19871. {
  19872. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19873. {
  19874. if (HasCompiledOutput())
  19875. EmitGCMarkMembers();
  19876. }
  19877. else if (!mCurTypeInstance->IsObject())
  19878. {
  19879. }
  19880. }
  19881. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  19882. {
  19883. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19884. {
  19885. if (HasCompiledOutput())
  19886. EmitGCFindTLSMembers();
  19887. }
  19888. }
  19889. }
  19890. }
  19891. else if (!skipBody)
  19892. {
  19893. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  19894. bool wantsRetVal = true;
  19895. if ((mIsComptimeModule) && (methodDef->mMethodType != BfMethodType_CtorCalcAppend))
  19896. wantsRetVal = false;
  19897. else if (mCurMethodInstance->mReturnType->IsVar())
  19898. wantsRetVal = false;
  19899. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  19900. {
  19901. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  19902. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  19903. {
  19904. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  19905. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  19906. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst, mCurMethodInstance->mReturnType->mAlign);
  19907. mBfIRBuilder->ClearDebugLocation(storeInst);
  19908. mCurMethodState->mRetValAddr = allocaInst;
  19909. }
  19910. else if (wantsRetVal)
  19911. {
  19912. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  19913. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  19914. }
  19915. }
  19916. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19917. {
  19918. mBfIRBuilder->CreateAlignedStore(GetConstValue(0), mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19919. BfGetSymbolReferenceKind prevSymbolKind;
  19920. BfAutoComplete* prevAutoComplete;
  19921. if (mCompiler->mResolvePassData != NULL)
  19922. {
  19923. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  19924. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19925. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  19926. }
  19927. EmitCtorCalcAppend();
  19928. if (mCompiler->mResolvePassData != NULL)
  19929. {
  19930. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  19931. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  19932. }
  19933. }
  19934. else if (!isEmptyBodied)
  19935. {
  19936. if (!mCurMethodState->mIRExitBlock)
  19937. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  19938. bool isExpressionBody = false;
  19939. if (methodDeclaration != NULL)
  19940. {
  19941. if (methodDeclaration->mFatArrowToken != NULL)
  19942. isExpressionBody = true;
  19943. }
  19944. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  19945. {
  19946. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  19947. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  19948. isExpressionBody = true;
  19949. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  19950. {
  19951. isExpressionBody = true;
  19952. }
  19953. }
  19954. else
  19955. {
  19956. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  19957. {
  19958. if (!block->mChildArr.IsEmpty())
  19959. {
  19960. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  19961. {
  19962. if (exprStmt->mTrailingSemicolon == NULL)
  19963. isExpressionBody = true;
  19964. }
  19965. }
  19966. }
  19967. else
  19968. isExpressionBody = true;
  19969. }
  19970. DoCEEmit(methodInstance);
  19971. if (methodInstance->mCeCancelled)
  19972. mIgnoreErrors = true;
  19973. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  19974. {
  19975. while (fieldDtorBody != NULL)
  19976. {
  19977. VisitEmbeddedStatement(fieldDtorBody->mBody);
  19978. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  19979. }
  19980. }
  19981. else if (!isExpressionBody)
  19982. {
  19983. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  19984. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  19985. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  19986. VisitCodeBlock(bodyBlock);
  19987. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  19988. }
  19989. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  19990. {
  19991. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  19992. // {
  19993. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  19994. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  19995. // }
  19996. auto expectingType = mCurMethodInstance->mReturnType;
  19997. // What was this error for?
  19998. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  19999. // {
  20000. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  20001. // }
  20002. BfEvalExprFlags exprEvalFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_IsExpressionBody);
  20003. if (expectingType->IsVoid())
  20004. {
  20005. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  20006. bool wasReturnGenericParam = false;
  20007. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  20008. {
  20009. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  20010. }
  20011. else
  20012. {
  20013. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  20014. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  20015. wasReturnGenericParam = true;
  20016. }
  20017. // If we the void return was from a generic specialization, allow us to return a void result,
  20018. // otherwise treat expression as though it must be a statement
  20019. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  20020. if (isStatement)
  20021. expectingType = NULL;
  20022. }
  20023. BfExprEvaluator exprEvaluator(this);
  20024. if (mCurMethodInstance->mMethodDef->mIsReadOnly)
  20025. exprEvaluator.mAllowReadOnlyReference = true;
  20026. UpdateSrcPos(expressionBody);
  20027. auto retVal = CreateValueFromExpression(exprEvaluator, expressionBody, expectingType, exprEvalFlags);
  20028. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  20029. {
  20030. mCurMethodState->mHadReturn = true;
  20031. if (!mCurMethodState->mLeftBlockUncond)
  20032. {
  20033. retVal = LoadOrAggregateValue(retVal);
  20034. EmitReturn(retVal);
  20035. }
  20036. }
  20037. }
  20038. }
  20039. }
  20040. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  20041. if (skipUpdateSrcPos)
  20042. {
  20043. // Skip
  20044. }
  20045. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  20046. UpdateSrcPos(bodyBlock->mCloseBrace);
  20047. else if (methodDef->mBody != NULL)
  20048. UpdateSrcPos(methodDef->mBody);
  20049. else if (methodDeclaration != NULL)
  20050. UpdateSrcPos(methodDeclaration);
  20051. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  20052. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  20053. else
  20054. UseDefaultSrcPos();
  20055. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  20056. {
  20057. if (mCurMethodState->mRetVal)
  20058. {
  20059. mCurMethodState->SetHadReturn(true);
  20060. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  20061. mBfIRBuilder->CreateRet(retVal);
  20062. }
  20063. else
  20064. AssertErrorState();
  20065. }
  20066. mCurMethodState->mHeadScope.mDone = true;
  20067. if (!mCurMethodState->mHadReturn)
  20068. {
  20069. // Clear off the stackallocs that have occurred after a scopeData break
  20070. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  20071. }
  20072. EmitDeferredCallProcessorInstances(&mCurMethodState->mHeadScope);
  20073. if (mCurMethodState->mIRExitBlock)
  20074. {
  20075. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  20076. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  20077. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  20078. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  20079. if ((!mCurMethodState->mDIRetVal) && (wantsDIData))
  20080. CreateDIRetVal();
  20081. }
  20082. for (auto localVar : mCurMethodState->mLocals)
  20083. {
  20084. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  20085. {
  20086. //
  20087. }
  20088. else if ((skipEndChecks) || (methodDef->mBody == NULL))
  20089. break;
  20090. LocalVariableDone(localVar, true);
  20091. }
  20092. if (mCurMethodState->mIRExitBlock)
  20093. {
  20094. if ((mCurMethodState->mRetVal) &&
  20095. ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() == -1)))
  20096. {
  20097. auto loadedVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  20098. CreateReturn(loadedVal);
  20099. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  20100. if (mCurMethodState->mDIRetVal)
  20101. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  20102. }
  20103. else
  20104. {
  20105. // Have something on the last line to step onto
  20106. if (mHasFullDebugInfo)
  20107. {
  20108. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  20109. UpdateSrcPos(bodyBlock->mCloseBrace);
  20110. EmitEnsureInstructionAt();
  20111. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  20112. {
  20113. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  20114. mBfIRBuilder->EnsureFunctionPatchable();
  20115. }
  20116. }
  20117. mBfIRBuilder->CreateRetVoid();
  20118. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  20119. if (mCurMethodState->mDIRetVal)
  20120. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  20121. }
  20122. }
  20123. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  20124. {
  20125. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  20126. {
  20127. if ((!mIsComptimeModule) && (irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  20128. {
  20129. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  20130. mBfIRBuilder->EnsureFunctionPatchable();
  20131. }
  20132. mBfIRBuilder->CreateRetVoid();
  20133. }
  20134. }
  20135. else
  20136. {
  20137. if (!mCurMethodState->mHadReturn)
  20138. {
  20139. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  20140. if (bodyBlock != NULL)
  20141. {
  20142. if (bodyBlock->mCloseBrace != NULL)
  20143. {
  20144. BfAstNode* target = bodyBlock->mCloseBrace;
  20145. if (!mCompiler->mHasRequiredTypes)
  20146. {
  20147. AddFailType(mCurTypeInstance);
  20148. mHadBuildError = true;
  20149. }
  20150. else
  20151. Fail("Method must return value", target);
  20152. }
  20153. else
  20154. {
  20155. // It's possible to not have a closing brace if the method ends in an EOF
  20156. AssertErrorState();
  20157. }
  20158. }
  20159. }
  20160. }
  20161. // Move 'init' into 'entry'
  20162. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  20163. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  20164. if (((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType())) &&
  20165. (!mIsComptimeModule))
  20166. {
  20167. // Don't keep instructions for unspecialized types
  20168. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  20169. }
  20170. // Avoid linking any internal funcs that were just supposed to be comptime-accessible
  20171. /*if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  20172. wantsRemoveBody = true;*/
  20173. if ((hasExternSpecifier) && (!skipBody))
  20174. {
  20175. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  20176. // incase it gets called later by some hot-loaded coded
  20177. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()) && (mCurTypeInstance != mContext->mBfObjectType))
  20178. {
  20179. if (!mCurMethodInstance->mMethodDef->mName.StartsWith("Comptime_"))
  20180. CreateFakeCallerMethod(mangledName);
  20181. }
  20182. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  20183. }
  20184. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  20185. {
  20186. // We only need the DLL stub when we may be hot swapping
  20187. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  20188. }
  20189. else if (wantsRemoveBody)
  20190. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  20191. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  20192. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  20193. // unspecialized types
  20194. if (((mCurTypeInstance->IsUnspecializedType()) && (!mIsComptimeModule)) ||
  20195. (mCurTypeInstance->IsInterface()))
  20196. {
  20197. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  20198. methodInstance->mIRFunction = BfIRFunction();
  20199. }
  20200. CheckAddFailType();
  20201. if (mHadBuildError)
  20202. prevHadBuildError.CancelRestore();
  20203. if (mHadBuildWarning)
  20204. prevHadWarning.CancelRestore();
  20205. if (!methodDef->mIsLocalMethod)
  20206. ProcessMethod_ProcessDeferredLocals();
  20207. prevIgnoreWrites.Restore();
  20208. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  20209. if (methodState.mHotDataReferenceBuilder != NULL)
  20210. {
  20211. AddHotDataReferences(&hotDataReferenceBuilder);
  20212. }
  20213. else
  20214. {
  20215. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  20216. {
  20217. // Remove the hot method data
  20218. auto hotMethod = methodInstance->mHotMethod;
  20219. auto prevMethod = hotMethod->mPrevVersion;
  20220. if (prevMethod != NULL)
  20221. {
  20222. // If there's a prev method then pull its data into the main HotMethod.
  20223. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  20224. // over to the main HotMethod definition to keep the HotMethod address
  20225. // invariant
  20226. for (auto ref : hotMethod->mReferences)
  20227. ref->Deref();
  20228. hotMethod->mReferences.Clear();
  20229. BF_ASSERT(prevMethod->mRefCount == 1);
  20230. hotMethod->mReferences = prevMethod->mReferences;
  20231. if (hotMethod->mSrcTypeVersion != NULL)
  20232. hotMethod->mSrcTypeVersion->Deref();
  20233. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  20234. prevMethod->mSrcTypeVersion = NULL;
  20235. prevMethod->mReferences.Clear();
  20236. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  20237. prevMethod->mPrevVersion = NULL;
  20238. prevMethod->Deref();
  20239. }
  20240. hotMethod->Deref();
  20241. methodInstance->mHotMethod = NULL;
  20242. }
  20243. }
  20244. }
  20245. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  20246. {
  20247. String name;
  20248. bool found = false;
  20249. auto checkMethodState = mCurMethodState;
  20250. while (checkMethodState != NULL)
  20251. {
  20252. if (checkMethodState->mClosureState == NULL)
  20253. break;
  20254. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  20255. {
  20256. found = true;
  20257. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  20258. break;
  20259. }
  20260. checkMethodState = checkMethodState->mPrevMethodState;
  20261. }
  20262. if (!found)
  20263. name += mCurMethodInstance->mMethodDef->mName;
  20264. int prevSepPos = (int)name.LastIndexOf('$');
  20265. if (prevSepPos != -1)
  20266. {
  20267. name.RemoveToEnd(prevSepPos);
  20268. }
  20269. name += "@";
  20270. name += baseName;
  20271. HashContext hashCtx;
  20272. if (anchorNode != NULL)
  20273. {
  20274. hashCtx.Mixin(anchorNode->GetStartCharId());
  20275. }
  20276. //
  20277. {
  20278. auto checkMethodState = declMethodState;
  20279. auto checkMixinState = declMixinState;
  20280. while (checkMethodState != NULL)
  20281. {
  20282. if (checkMixinState != NULL)
  20283. {
  20284. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  20285. }
  20286. checkMethodState = checkMethodState->mPrevMethodState;
  20287. if (checkMethodState != NULL)
  20288. checkMixinState = checkMethodState->mMixinState;
  20289. }
  20290. }
  20291. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20292. if ((rootMethodState != NULL) && (rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  20293. {
  20294. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  20295. {
  20296. StringT<512> genericTypeName;
  20297. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  20298. hashCtx.MixinStr(genericTypeName);
  20299. }
  20300. }
  20301. uint64 hashVal = hashCtx.Finish64();
  20302. name += "$";
  20303. name += BfTypeUtils::HashEncode64(hashVal);
  20304. return name;
  20305. }
  20306. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  20307. {
  20308. if (localMethod->mMethodDef != NULL)
  20309. return localMethod->mMethodDef;
  20310. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20311. auto declMethodState = localMethod->mDeclMethodState;
  20312. auto declMixinState = localMethod->mDeclMixinState;
  20313. auto typeInst = mCurTypeInstance;
  20314. BfAstNode* body = NULL;
  20315. BfAstNode* anchorNode = NULL;
  20316. auto _AllocDirectTypeRef = [&](BfType* type)
  20317. {
  20318. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  20319. directTypeRef->Init(type);
  20320. return directTypeRef;
  20321. };
  20322. auto methodDeclaration = localMethod->mMethodDeclaration;
  20323. if (methodDeclaration != NULL)
  20324. {
  20325. body = methodDeclaration->mBody;
  20326. anchorNode = methodDeclaration->mOpenParen;
  20327. }
  20328. else
  20329. {
  20330. body = localMethod->mLambdaBindExpr->mBody;
  20331. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  20332. }
  20333. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  20334. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  20335. BfMethodDef* methodDef;
  20336. BfMethodDef* outerMethodDef = NULL;
  20337. if (localMethod->mOuterLocalMethod != NULL)
  20338. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  20339. else if (rootMethodState->mMethodInstance != NULL)
  20340. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  20341. if (methodDeclaration != NULL)
  20342. {
  20343. BfDefBuilder defBuilder(mCompiler->mSystem);
  20344. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  20345. defBuilder.mPassInstance = mCompiler->mPassInstance;
  20346. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  20347. defBuilder.mCurDeclaringTypeDef = defBuilder.mCurTypeDef;
  20348. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  20349. }
  20350. else
  20351. {
  20352. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  20353. methodDef = new BfMethodDef();
  20354. methodDef->mName = localMethod->mMethodName;
  20355. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  20356. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  20357. methodDef->mBody = body;
  20358. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  20359. {
  20360. auto paramType = invokeMethod->GetParamType(paramIdx);
  20361. String paramName;
  20362. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  20363. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  20364. else
  20365. paramName = invokeMethod->GetParamName(paramIdx);
  20366. auto paramDef = new BfParameterDef();
  20367. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  20368. paramDef->mName = paramName;
  20369. methodDef->mParams.Add(paramDef);
  20370. }
  20371. if (outerMethodDef != NULL)
  20372. {
  20373. for (auto genericParam : outerMethodDef->mGenericParams)
  20374. {
  20375. auto* copiedGenericParamDef = new BfGenericParamDef();
  20376. *copiedGenericParamDef = *genericParam;
  20377. methodDef->mGenericParams.Add(copiedGenericParamDef);
  20378. }
  20379. }
  20380. }
  20381. methodDef->mIdx = ~methodLocalIdx;
  20382. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  20383. methodDef->mName = localMethod->mExpectedFullName;
  20384. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  20385. //
  20386. // if (!localMethod->mExpectedFullName.IsEmpty())
  20387. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  20388. methodDef->mIsStatic = true;
  20389. methodDef->mIsLocalMethod = true;
  20390. methodDef->mIsVirtual = false;
  20391. localMethod->mMethodDef = methodDef;
  20392. auto methodInstanceGroup = new BfMethodInstanceGroup();
  20393. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  20394. methodInstanceGroup->mMethodIdx = -1;
  20395. methodInstanceGroup->mOwner = mCurTypeInstance;
  20396. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  20397. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  20398. {
  20399. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  20400. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  20401. }
  20402. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  20403. {
  20404. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  20405. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  20406. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  20407. {
  20408. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  20409. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  20410. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  20411. autoComplete->mDefType = typeInst->mTypeDef;
  20412. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  20413. autoComplete->mReplaceLocalId = methodLocalIdx;
  20414. }
  20415. }
  20416. return localMethod->mMethodDef;
  20417. }
  20418. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  20419. {
  20420. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  20421. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  20422. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20423. auto declMethodState = localMethod->mDeclMethodState;
  20424. auto declMixinState = localMethod->mDeclMixinState;
  20425. auto callerMethodState = mCurMethodState;
  20426. auto typeInst = mCurTypeInstance;
  20427. if (mCurMethodState->mMixinState != NULL)
  20428. {
  20429. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  20430. }
  20431. auto methodDef = GetLocalMethodDef(localMethod);
  20432. BfAstNode* body = NULL;
  20433. auto methodDeclaration = localMethod->mMethodDeclaration;
  20434. if (methodDeclaration != NULL)
  20435. {
  20436. body = methodDeclaration->mBody;
  20437. }
  20438. else
  20439. {
  20440. body = localMethod->mLambdaBindExpr->mBody;
  20441. }
  20442. bool hadConcreteInterfaceGenericArgument = false;
  20443. BfTypeVector sanitizedMethodGenericArguments;
  20444. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  20445. // version of this method for this pass through the outermost method
  20446. int dependentGenericStartIdx = 0;
  20447. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  20448. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  20449. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  20450. if (methodGenericArguments.size() == 0)
  20451. {
  20452. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  20453. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  20454. }
  20455. else
  20456. {
  20457. int genericArgIdx = 0;
  20458. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  20459. // {
  20460. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  20461. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  20462. // }
  20463. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  20464. {
  20465. auto genericArgType = methodGenericArguments[genericArgIdx];
  20466. BF_ASSERT(!genericArgType->IsRef());
  20467. if (genericArgType->IsConcreteInterfaceType())
  20468. {
  20469. hadConcreteInterfaceGenericArgument = true;
  20470. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  20471. genericArgType = concreteInterfaceType->mInterface;
  20472. }
  20473. sanitizedMethodGenericArguments.push_back(genericArgType);
  20474. }
  20475. }
  20476. bool wantPrematureMethodInstance = false;
  20477. if (!force)
  20478. {
  20479. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  20480. }
  20481. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  20482. bool isDefaultPass = true;
  20483. BfTypeVector lookupMethodGenericArguments;
  20484. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  20485. {
  20486. auto genericArgType = methodGenericArguments[genericArgIdx];
  20487. BF_ASSERT(!genericArgType->IsRef());
  20488. lookupMethodGenericArguments.Add(genericArgType);
  20489. if (genericArgType->IsGenericParam())
  20490. {
  20491. auto genericParam = (BfGenericParamType*)genericArgType;
  20492. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  20493. isDefaultPass = false;
  20494. }
  20495. else
  20496. {
  20497. isDefaultPass = false;
  20498. }
  20499. }
  20500. bool hadExistingMethodInstance = false;
  20501. if (methodInstance != NULL)
  20502. {
  20503. hadExistingMethodInstance = true;
  20504. }
  20505. else
  20506. {
  20507. if (isDefaultPass)
  20508. {
  20509. methodInstance = methodInstGroup->mDefault;
  20510. if (methodInstance != NULL)
  20511. {
  20512. hadExistingMethodInstance = true;
  20513. }
  20514. else
  20515. {
  20516. methodInstance = new BfMethodInstance();
  20517. methodInstGroup->mDefault = methodInstance;
  20518. }
  20519. }
  20520. else
  20521. {
  20522. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  20523. if (methodInstGroup->mMethodSpecializationMap == NULL)
  20524. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  20525. BfMethodInstance** methodInstancePtr = NULL;
  20526. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  20527. {
  20528. methodInstance = *methodInstancePtr;
  20529. hadExistingMethodInstance = true;
  20530. }
  20531. else
  20532. {
  20533. methodInstance = new BfMethodInstance();
  20534. *methodInstancePtr = methodInstance;
  20535. }
  20536. }
  20537. }
  20538. if (hadExistingMethodInstance)
  20539. {
  20540. if ((!methodInstance->mDisallowCalling) ||
  20541. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  20542. return BfModuleMethodInstance(methodInstance);
  20543. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  20544. }
  20545. else
  20546. {
  20547. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  20548. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  20549. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  20550. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  20551. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  20552. methodInstance->mMethodDef = methodDef;
  20553. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  20554. if (hadConcreteInterfaceGenericArgument)
  20555. methodInstance->mIgnoreBody = true;
  20556. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  20557. for (auto genericArg : sanitizedMethodGenericArguments)
  20558. {
  20559. if (genericArg->IsPrimitiveType())
  20560. genericArg = GetWrappedStructType(genericArg);
  20561. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  20562. }
  20563. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  20564. {
  20565. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  20566. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  20567. }
  20568. SetupMethodIdHash(methodInstance);
  20569. }
  20570. auto _SetupMethodInstance = [&]()
  20571. {
  20572. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  20573. // Generic constraints
  20574. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  20575. {
  20576. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  20577. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  20578. }
  20579. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  20580. {
  20581. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  20582. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  20583. }
  20584. };
  20585. //////////////////////////////////////////////////////////////////////////
  20586. auto _VisitLambdaBody = [&]()
  20587. {
  20588. if (localMethod->mDeclOnly)
  20589. return;
  20590. if (mCompiler->mCanceling)
  20591. return;
  20592. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  20593. {
  20594. VisitCodeBlock(blockBody);
  20595. }
  20596. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  20597. {
  20598. BfType* expectType = NULL;
  20599. if (!methodInstance->mReturnType->IsVoid())
  20600. expectType = methodInstance->mReturnType;
  20601. CreateValueFromExpression(bodyExpr, expectType, BfEvalExprFlags_AllowRefExpr);
  20602. }
  20603. };
  20604. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  20605. {
  20606. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  20607. auto result = ResolveTypeRef(typeRef);
  20608. if (result == NULL)
  20609. result = mContext->mBfObjectType;
  20610. return result;
  20611. };
  20612. BfTypeInstance* outerClosure = NULL;
  20613. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  20614. outerClosure = declMethodState->mClosureState->mClosureType;
  20615. BfMethodState methodState;
  20616. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  20617. BfIRFunctionType funcType;
  20618. auto voidType = GetPrimitiveType(BfTypeCode_None);
  20619. SizedArray<BfIRType, 0> paramTypes;
  20620. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  20621. mBfIRBuilder->SaveDebugLocation();
  20622. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  20623. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  20624. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  20625. BfDeferredLocalAssignData deferredLocalAssignData;
  20626. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  20627. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  20628. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  20629. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  20630. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  20631. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  20632. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  20633. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  20634. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  20635. methodState.mIRFunction = declMethodState->mIRFunction;
  20636. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  20637. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  20638. {
  20639. methodState.mCurScope->mAstBlock = blockBody;
  20640. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  20641. }
  20642. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  20643. BfClosureState closureState;
  20644. if (methodDef->mMethodType == BfMethodType_Mixin)
  20645. {
  20646. if (declMethodState != NULL)
  20647. {
  20648. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  20649. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  20650. else if (declMethodState->mMethodInstance != NULL)
  20651. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  20652. }
  20653. }
  20654. if (closureState.mReturnType == NULL)
  20655. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  20656. closureState.mCapturing = true;
  20657. closureState.mLocalMethod = localMethod;
  20658. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  20659. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  20660. methodState.mClosureState = &closureState;
  20661. closureState.mClosureType = outerClosure;
  20662. int outerLocalsCount = (int)methodState.mLocals.size();
  20663. if (!hadExistingMethodInstance)
  20664. {
  20665. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  20666. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  20667. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  20668. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  20669. auto declareModule = this;
  20670. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  20671. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  20672. BF_ASSERT(declareModule != NULL);
  20673. methodInstance->mDeclModule = declareModule;
  20674. _SetupMethodInstance();
  20675. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  20676. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  20677. }
  20678. if (wantPrematureMethodInstance)
  20679. {
  20680. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  20681. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  20682. // its true method instance
  20683. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  20684. //BF_ASSERT(moduleMethodInstance);
  20685. return BfModuleMethodInstance(methodInstance);
  20686. }
  20687. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  20688. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  20689. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  20690. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  20691. closureState.mClosureMethodDef = methodDef;
  20692. bool wantsVisitBody = true;
  20693. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  20694. wantsVisitBody = false;
  20695. if (methodInstance->IsOrInUnspecializedVariation())
  20696. wantsVisitBody = false;
  20697. bool allowCapture = (methodDeclaration == NULL) || (methodDeclaration->mStaticSpecifier == NULL);
  20698. if (wantsVisitBody)
  20699. {
  20700. BP_ZONE("VisitLambdaBody");
  20701. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  20702. // this capture stage for each of those times
  20703. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  20704. /*
  20705. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  20706. // that will not occur during the actual lambda method generation, for example: returning a value
  20707. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  20708. // our AST nodes will still be visited
  20709. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  20710. */
  20711. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20712. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  20713. mBfIRBuilder->SaveDebugLocation();
  20714. closureState.mCaptureVisitingBody = true;
  20715. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  20716. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  20717. methodState.mMethodInstance = methodInstance;
  20718. NewScopeState();
  20719. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  20720. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  20721. {
  20722. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  20723. for (auto localDef : methodState.mLocals)
  20724. {
  20725. if (localDef->mResolvedType->IsVar())
  20726. continue;
  20727. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  20728. }
  20729. }
  20730. // Keep outs from being marked as assigned
  20731. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20732. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  20733. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  20734. auto prevDLA = rootMethodState->mDeferredLocalAssignData;
  20735. while ((prevDLA != NULL) && (prevDLA->mIsChained))
  20736. prevDLA = prevDLA->mChainedAssignData;
  20737. if (prevDLA != NULL)
  20738. {
  20739. deferredLocalAssignData.mAssignedLocals = prevDLA->mAssignedLocals;
  20740. deferredLocalAssignData.mLeftBlockUncond = prevDLA->mLeftBlockUncond;
  20741. }
  20742. SetAndRestoreValue<BfDeferredLocalAssignData*> sarDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  20743. if (!mIgnoreErrors)
  20744. localMethod->mDidBodyErrorPass = true;
  20745. _VisitLambdaBody();
  20746. RestoreScopeState();
  20747. closureState.mCaptureVisitingBody = false;
  20748. mBfIRBuilder->RestoreDebugLocation();
  20749. }
  20750. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  20751. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  20752. {
  20753. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  20754. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  20755. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  20756. }
  20757. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  20758. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  20759. closureState.mClosureMethodDef = NULL;
  20760. for (auto methodInstance : closureState.mLocalMethodRefs)
  20761. {
  20762. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  20763. }
  20764. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  20765. prevIgnoreWrites.Restore();
  20766. std::multiset<BfClosureCapturedEntry> capturedEntries;
  20767. //
  20768. {
  20769. auto varMethodState = declMethodState;
  20770. while (varMethodState != NULL)
  20771. {
  20772. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  20773. {
  20774. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  20775. methodDef->mIsStatic = false;
  20776. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20777. methodDef->mIsMutating = true;
  20778. }
  20779. bool copyOuterCaptures = false;
  20780. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  20781. {
  20782. auto localVar = varMethodState->mLocals[localIdx];
  20783. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20784. {
  20785. if (!allowCapture)
  20786. {
  20787. if ((!localVar->mIsStatic) && (!localVar->mConstValue))
  20788. continue;
  20789. }
  20790. if (localVar->mIsThis)
  20791. {
  20792. // We can only set mutating if our owning type is mutating
  20793. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  20794. {
  20795. if (typeInst->IsValueType())
  20796. {
  20797. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20798. methodDef->mIsMutating = true;
  20799. }
  20800. }
  20801. methodDef->mIsStatic = false;
  20802. continue;
  20803. }
  20804. if ((localVar->mIsThis) && (outerClosure != NULL))
  20805. {
  20806. continue;
  20807. }
  20808. if ((localVar->mConstValue) || (localVar->mIsStatic) || (localVar->mResolvedType->IsValuelessType()))
  20809. {
  20810. closureState.mConstLocals.push_back(*localVar);
  20811. continue;
  20812. }
  20813. BfClosureCapturedEntry capturedEntry;
  20814. auto capturedType = localVar->mResolvedType;
  20815. bool captureByRef = false;
  20816. if (!capturedType->IsRef())
  20817. {
  20818. if (localVar->mIsThis)
  20819. {
  20820. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  20821. captureByRef = true;
  20822. }
  20823. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20824. captureByRef = true;
  20825. }
  20826. else
  20827. {
  20828. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  20829. {
  20830. capturedType = ((BfRefType*)capturedType)->mElementType;
  20831. }
  20832. }
  20833. if (captureByRef)
  20834. {
  20835. //capturedEntry.mIsByReference = true;
  20836. capturedType = CreateRefType(capturedType);
  20837. }
  20838. else
  20839. {
  20840. //capturedEntry.mIsByReference = false;
  20841. }
  20842. capturedEntry.mNameNode = localVar->mNameNode;
  20843. capturedEntry.mType = capturedType;
  20844. capturedEntry.mName = localVar->mName;
  20845. //capturedEntry.mLocalVarDef = localVar;
  20846. capturedEntries.insert(capturedEntry);
  20847. }
  20848. }
  20849. varMethodState = varMethodState->mPrevMethodState;
  20850. if ((varMethodState == NULL) ||
  20851. (varMethodState->mMixinState != NULL) ||
  20852. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  20853. break;
  20854. }
  20855. }
  20856. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  20857. {
  20858. auto fieldDef = copyField->GetFieldDef();
  20859. BfClosureCapturedEntry capturedEntry;
  20860. capturedEntry.mName = copyField->GetFieldDef()->mName;
  20861. capturedEntry.mType = copyField->mResolvedType;
  20862. if (capturedEntry.mType->IsRef())
  20863. {
  20864. // Keep by ref
  20865. }
  20866. else if (!fieldDef->mIsReadOnly)
  20867. {
  20868. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  20869. }
  20870. capturedEntries.insert(capturedEntry);
  20871. }
  20872. int captureIdx = 0;
  20873. for (auto& capturedEntry : capturedEntries)
  20874. {
  20875. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  20876. }
  20877. /*if (isDefaultPass)
  20878. {
  20879. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  20880. int captureIdx = 0;
  20881. for (auto& capturedEntry : capturedEntries)
  20882. {
  20883. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  20884. BfParameterDef* paramDef = new BfParameterDef();
  20885. paramDef->mName = capturedEntry.mName;
  20886. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  20887. directTypeRef->mType = capturedEntry.mType;
  20888. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  20889. paramDef->mTypeRef = directTypeRef;
  20890. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  20891. methodDef->mParams.Insert(captureIdx, paramDef);
  20892. captureIdx++;
  20893. }
  20894. }
  20895. else
  20896. {
  20897. auto defaultMethodInstance = methodInstGroup->mDefault;
  20898. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  20899. }*/
  20900. methodState.Reset();
  20901. closureState.mCapturing = false;
  20902. //////////////////////////////////////////////////////////////////////////
  20903. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  20904. if (methodInstance->mReturnType != NULL)
  20905. {
  20906. BF_ASSERT(methodInstance->mDisallowCalling);
  20907. // We did a premature declaration (without captures)
  20908. methodInstance->UndoDeclaration();
  20909. methodInstance->mDisallowCalling = false;
  20910. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  20911. }
  20912. auto declareModule = this;
  20913. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  20914. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  20915. BF_ASSERT(declareModule != NULL);
  20916. methodInstance->mDeclModule = declareModule;
  20917. _SetupMethodInstance();
  20918. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  20919. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  20920. closureState.mReturnType = methodInstance->mReturnType;
  20921. mCompiler->mStats.mMethodsQueued++;
  20922. mCompiler->UpdateCompletion();
  20923. declareModule->mIncompleteMethodCount++;
  20924. mCompiler->mStats.mMethodsProcessed++;
  20925. if (!methodInstance->mIsReified)
  20926. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  20927. auto deferMethodState = rootMethodState;
  20928. // 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)
  20929. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  20930. (methodDef->mMethodType != BfMethodType_Mixin) &&
  20931. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)) &&
  20932. (!mCompiler->IsDataResolvePass()))
  20933. {
  20934. BP_ZONE("BfDeferredLocalMethod:create");
  20935. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  20936. deferredLocalMethod->mLocalMethod = localMethod;
  20937. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  20938. deferredLocalMethod->mMethodInstance = methodInstance;
  20939. auto checkMethodState = declMethodState;
  20940. while (checkMethodState != NULL)
  20941. {
  20942. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  20943. {
  20944. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  20945. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20946. }
  20947. if (checkMethodState->mMixinState != NULL)
  20948. {
  20949. BfMixinRecord mixinRecord;
  20950. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  20951. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20952. }
  20953. checkMethodState = checkMethodState->mPrevMethodState;
  20954. }
  20955. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  20956. }
  20957. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  20958. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  20959. mBfIRBuilder->RestoreDebugLocation();
  20960. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  20961. {
  20962. auto checkMethodState = mCurMethodState;
  20963. while (checkMethodState != NULL)
  20964. {
  20965. BfLocalMethod* nextLocalMethod = NULL;
  20966. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  20967. {
  20968. while (nextLocalMethod != NULL)
  20969. {
  20970. auto checkLocalMethod = nextLocalMethod;
  20971. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  20972. if (checkLocalMethod == localMethod)
  20973. continue;
  20974. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  20975. continue;
  20976. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  20977. if (checkMethodInstance == NULL)
  20978. continue; // Not generated yet
  20979. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  20980. {
  20981. String error = "Method already declared with the same parameter types";
  20982. auto bfError = Fail(error, methodInstance->mMethodDef->GetRefNode(), true);
  20983. if ((bfError != NULL) && (methodInstance->mMethodDef->GetRefNode() != checkMethodInstance->mMethodDef->GetRefNode()))
  20984. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  20985. }
  20986. }
  20987. }
  20988. checkMethodState = checkMethodState->mPrevMethodState;
  20989. }
  20990. }
  20991. return BfModuleMethodInstance(methodInstance);
  20992. }
  20993. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  20994. {
  20995. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  20996. return 0;
  20997. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20998. int rootMethodGenericParamCount = 0;
  20999. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  21000. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  21001. if (mCurMethodInstance == NULL)
  21002. return rootMethodGenericParamCount;
  21003. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  21004. return rootMethodGenericParamCount;
  21005. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  21006. if (callerLocalMethod == NULL)
  21007. return rootMethodGenericParamCount;
  21008. BfLocalMethod* calledLocalMethod = NULL;
  21009. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  21010. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  21011. {
  21012. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  21013. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  21014. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  21015. }
  21016. return rootMethodGenericParamCount;
  21017. }
  21018. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  21019. {
  21020. auto methodDef = methodInstance->mMethodDef;
  21021. auto customAttributes = methodInstance->GetCustomAttributes();
  21022. if (customAttributes != NULL)
  21023. return;
  21024. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21025. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  21026. auto typeInstance = methodInstance->GetOwner();
  21027. if (typeInstance->IsInstanceOf(mCompiler->mValueTypeTypeDef))
  21028. return;
  21029. BfTypeState typeState(typeInstance);
  21030. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  21031. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  21032. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  21033. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  21034. BfAttributeDirective* attributeDirective = NULL;
  21035. if (methodDeclaration != NULL)
  21036. attributeDirective = methodDeclaration->mAttributes;
  21037. else if (propertyMethodDeclaration != NULL)
  21038. {
  21039. attributeDirective = propertyMethodDeclaration->mAttributes;
  21040. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  21041. {
  21042. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  21043. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  21044. }
  21045. }
  21046. if (attributeDirective != NULL)
  21047. {
  21048. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  21049. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  21050. if ((methodInstance == methodInstance->mMethodInstanceGroup->mDefault) && (methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes != NULL))
  21051. {
  21052. // Take over previously-generated custom attributes
  21053. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes;
  21054. methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes = NULL;
  21055. }
  21056. else
  21057. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  21058. }
  21059. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mPropertyDeclaration->mAttributes != NULL) && ((attrTarget & BfAttributeTargets_Property) == 0))
  21060. {
  21061. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes != NULL)
  21062. {
  21063. GetCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  21064. }
  21065. else
  21066. {
  21067. methodInstance->GetMethodInfoEx()->mMethodCustomAttributes = new BfMethodCustomAttributes();
  21068. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  21069. }
  21070. }
  21071. if (methodDeclaration != NULL)
  21072. {
  21073. if (auto inlineTypeRef = BfNodeDynCast<BfInlineTypeReference>(methodDeclaration->mReturnType))
  21074. {
  21075. if (inlineTypeRef->mTypeDeclaration->mAttributes != NULL)
  21076. {
  21077. // Apply multiuse attributes from anonymous return type
  21078. auto returnType = ResolveTypeRef(inlineTypeRef);
  21079. if ((returnType != NULL) && (returnType->ToTypeInstance()))
  21080. {
  21081. auto returnTypeInst = returnType->ToTypeInstance();
  21082. if ((returnTypeInst->IsAnonymous()) && (returnTypeInst->mCustomAttributes != NULL))
  21083. {
  21084. bool hasPendingAttributes = false;
  21085. for (const auto& customAttribute : returnTypeInst->mCustomAttributes->mAttributes)
  21086. {
  21087. if (customAttribute.mAwaitingValidation)
  21088. {
  21089. hasPendingAttributes = true;
  21090. break;
  21091. }
  21092. }
  21093. if (hasPendingAttributes)
  21094. {
  21095. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  21096. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  21097. if (methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes == NULL)
  21098. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = new BfCustomAttributes();
  21099. for (const auto& customAttribute : returnTypeInst->mCustomAttributes->mAttributes)
  21100. {
  21101. if (!customAttribute.mAwaitingValidation)
  21102. continue;
  21103. BfCustomAttribute copiedCustomAttribute = customAttribute;
  21104. copiedCustomAttribute.mIsMultiUse = false;
  21105. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes.Add(copiedCustomAttribute);
  21106. }
  21107. ValidateCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, attrTarget);
  21108. }
  21109. }
  21110. }
  21111. }
  21112. }
  21113. }
  21114. customAttributes = methodInstance->GetCustomAttributes();
  21115. if (customAttributes == NULL)
  21116. {
  21117. auto owner = methodInstance->GetOwner();
  21118. if ((owner->IsDelegate()) || (owner->IsFunction()))
  21119. customAttributes = owner->mCustomAttributes;
  21120. }
  21121. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  21122. if ((typeInstance->IsValueType()) && (methodDef->mIsOverride) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS))
  21123. {
  21124. // Make sure we we pass 'this' as a pointer into GCMarkMembers so it's compatible with the mark function pointer
  21125. methodInstance->mCallingConvention = BfCallingConvention_Cdecl;
  21126. }
  21127. if (customAttributes != NULL)
  21128. {
  21129. if (customAttributes->Contains(mCompiler->mIntrinsicAttributeTypeDef))
  21130. methodInstance->mIsIntrinsic = true;
  21131. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  21132. if (linkNameAttr != NULL)
  21133. {
  21134. if (linkNameAttr->mCtorArgs.size() == 1)
  21135. {
  21136. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  21137. if (constant != NULL)
  21138. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  21139. }
  21140. }
  21141. if (methodDef->mHasComptime)
  21142. methodInstance->mComptimeFlags = BfComptimeFlag_Comptime;
  21143. auto comptimeAttr = customAttributes->Get(mCompiler->mComptimeAttributeTypeDef);
  21144. if (comptimeAttr != NULL)
  21145. {
  21146. for (auto setProp : comptimeAttr->mSetProperties)
  21147. {
  21148. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  21149. if (propertyDef->mName == "OnlyFromComptime")
  21150. {
  21151. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  21152. if ((constant != NULL) && (constant->mBool))
  21153. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_OnlyFromComptime);
  21154. }
  21155. else if (propertyDef->mName == "ConstEval")
  21156. {
  21157. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  21158. if ((constant != NULL) && (constant->mBool))
  21159. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_ConstEval);
  21160. }
  21161. }
  21162. }
  21163. }
  21164. auto delegateInfo = typeInstance->GetDelegateInfo();
  21165. if ((delegateInfo != NULL) && (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) && (methodInstance->mMethodDef->mName == "Invoke"))
  21166. methodInstance->mCallingConvention = delegateInfo->mCallingConvention;
  21167. }
  21168. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  21169. {
  21170. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  21171. {
  21172. // Don't create a func
  21173. return;
  21174. }
  21175. auto typeInstance = methodInstance->GetOwner();
  21176. auto methodDef = methodInstance->mMethodDef;
  21177. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  21178. if (isTemporaryFunc)
  21179. {
  21180. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  21181. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  21182. mangledName = "autocomplete_tmp";
  21183. }
  21184. if (!mBfIRBuilder->mIgnoreWrites)
  21185. {
  21186. BfIRFunction prevFunc;
  21187. // Remove old version (if we have one)
  21188. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  21189. if (prevFunc)
  21190. {
  21191. auto owner = methodInstance->GetOwner();
  21192. if ((methodDef->mIsOverride) && (owner->mTypeDef->mIsCombinedPartial))
  21193. {
  21194. bool takeover = false;
  21195. owner->mTypeDef->PopulateMemberSets();
  21196. BfMethodDef* nextMethod = NULL;
  21197. BfMemberSetEntry* entry = NULL;
  21198. if (owner->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21199. nextMethod = (BfMethodDef*)entry->mMemberDef;
  21200. while (nextMethod != NULL)
  21201. {
  21202. auto checkMethod = nextMethod;
  21203. nextMethod = nextMethod->mNextWithSameName;
  21204. if (checkMethod == methodDef)
  21205. continue;
  21206. if (checkMethod->mIsOverride)
  21207. {
  21208. auto checkMethodInstance = owner->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21209. if (checkMethodInstance == NULL)
  21210. continue;
  21211. if ((checkMethodInstance->mIRFunction == prevFunc) &&
  21212. (checkMethodInstance->mMethodDef->mMethodDeclaration != NULL) &&
  21213. (checkMethodInstance->mVirtualTableIdx < 0))
  21214. {
  21215. BfAstNode* refNode = methodDef->GetRefNode();
  21216. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  21217. refNode = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  21218. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21219. refNode = methodDeclaration->mVirtualSpecifier;
  21220. auto error = Fail(StrFormat("Conflicting extension override method '%s'", MethodToString(methodInstance).c_str()), refNode);
  21221. if (error != NULL)
  21222. mCompiler->mPassInstance->MoreInfo("See previous override", checkMethod->GetRefNode());
  21223. takeover = false;
  21224. break;
  21225. }
  21226. }
  21227. if (!checkMethod->mIsExtern)
  21228. continue;
  21229. auto checkMethodInstance = owner->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21230. if (checkMethodInstance == NULL)
  21231. continue;
  21232. if (!CompareMethodSignatures(checkMethodInstance, methodInstance))
  21233. continue;
  21234. // Take over function
  21235. takeover = true;
  21236. BfLogSysM("Method %p setting mHasBeenProcessed due to funcId takeover from method %p\n", checkMethodInstance, prevFunc.mId, methodInstance);
  21237. checkMethodInstance->mHasBeenProcessed = true;
  21238. }
  21239. if (takeover)
  21240. {
  21241. BfLogSysM("Method %p takover of previous funcId: %d\n", methodInstance, prevFunc.mId);
  21242. methodInstance->mIRFunction = prevFunc;
  21243. }
  21244. if (!methodInstance->mIRFunction)
  21245. {
  21246. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  21247. if (!mIsComptimeModule)
  21248. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  21249. }
  21250. }
  21251. else if (methodDef->mIsExtern)
  21252. {
  21253. // Allow this
  21254. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  21255. }
  21256. else if (typeInstance->IsIRFuncUsed(prevFunc))
  21257. {
  21258. // We can have a collision of names when we have generic methods that differ only in
  21259. // their constraints, but they should only collide in their unspecialized form
  21260. // since only one will be chosen for a given concrete type
  21261. if (!mIsComptimeModule)
  21262. methodInstance->mMangleWithIdx = true;
  21263. mangledName.Clear();
  21264. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  21265. BfLogSysM("Function collision forced mangleWithIdx for %p: %d GenericArgs: %d Unspecialized: %d\n", methodInstance, prevFunc.mId, methodInstance->GetNumGenericArguments(), methodInstance->mIsUnspecialized);
  21266. }
  21267. else
  21268. {
  21269. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  21270. if (!mIsComptimeModule)
  21271. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  21272. }
  21273. }
  21274. }
  21275. if (typeInstance != mContext->mBfObjectType)
  21276. {
  21277. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  21278. GetMethodCustomAttributes(methodInstance);
  21279. }
  21280. bool isIntrinsic = false;
  21281. if (!methodInstance->mIRFunction)
  21282. {
  21283. BfIRFunction func;
  21284. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType() || (mIsComptimeModule)) &&
  21285. (!methodDef->IsEmptyPartial())) && (funcType);
  21286. if (wantsLLVMFunc)
  21287. {
  21288. func = GetIntrinsic(methodInstance, true);
  21289. if (func)
  21290. {
  21291. isIntrinsic = true;
  21292. }
  21293. else
  21294. {
  21295. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  21296. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  21297. if (methodInstance->mAlwaysInline)
  21298. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  21299. }
  21300. methodInstance->mIRFunction = func;
  21301. }
  21302. }
  21303. if (outIsIntrinsic != NULL)
  21304. *outIsIntrinsic = isIntrinsic;
  21305. if (!isIntrinsic)
  21306. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  21307. }
  21308. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  21309. {
  21310. if (methodInstance->mHotMethod != NULL)
  21311. return;
  21312. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  21313. {
  21314. auto srcTypeInst = methodInstance->GetOwner();
  21315. if (srcTypeInst->mHotTypeData == NULL)
  21316. return;
  21317. StringT<128> mangledName = inMangledName;
  21318. if (mangledName.IsEmpty())
  21319. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  21320. // We always keep the current primary method at the same address
  21321. BfHotMethod* hotMethod;
  21322. BfHotMethod** hotMethodPtr;
  21323. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  21324. {
  21325. hotMethod = new BfHotMethod();
  21326. *hotMethodPtr = hotMethod;
  21327. hotMethod->mRefCount = 1;
  21328. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  21329. #ifdef BF_DBG_HOTMETHOD_IDX
  21330. static int sMethodIdx = 0;
  21331. hotMethod->mMethodIdx = sMethodIdx++;
  21332. #endif
  21333. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  21334. }
  21335. else
  21336. {
  21337. hotMethod = *hotMethodPtr;
  21338. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  21339. {
  21340. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  21341. auto prevHotMethod = *hotMethodPtr;
  21342. hotMethod = new BfHotMethod();
  21343. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  21344. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  21345. hotDupMethod->mRefCount++;
  21346. prevHotMethod->mReferences.Add(hotDupMethod);
  21347. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  21348. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  21349. }
  21350. else if (mCompiler->IsHotCompile())
  21351. {
  21352. // Link the previous version into the mPrevVersion
  21353. BfHotMethod* prevMethod = new BfHotMethod();
  21354. prevMethod->mRefCount = 1;
  21355. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  21356. hotMethod->mPrevVersion = prevMethod;
  21357. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  21358. hotMethod->mSrcTypeVersion = NULL;
  21359. prevMethod->mFlags = hotMethod->mFlags;
  21360. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  21361. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  21362. #ifdef BF_DBG_HOTMETHOD_NAME
  21363. prevMethod->mMangledName = hotMethod->mMangledName;
  21364. #endif
  21365. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  21366. }
  21367. else
  21368. {
  21369. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  21370. hotMethod->Clear(true);
  21371. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  21372. }
  21373. }
  21374. if (methodInstance->mIsClosure)
  21375. {
  21376. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  21377. }
  21378. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  21379. hotMethod->mSrcTypeVersion->mRefCount++;
  21380. hotMethod->mRefCount++;
  21381. #ifdef BF_DBG_HOTMETHOD_NAME
  21382. hotMethod->mMangledName = mangledName;
  21383. #endif
  21384. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!IsHotCompile()))
  21385. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  21386. methodInstance->mHotMethod = hotMethod;
  21387. }
  21388. }
  21389. static void StackOverflow()
  21390. {
  21391. int i = 0;
  21392. if (i == 0)
  21393. StackOverflow();
  21394. }
  21395. void BfModule::StartMethodDeclaration(BfMethodInstance* methodInstance, BfMethodState* prevMethodState)
  21396. {
  21397. methodInstance->mHasStartedDeclaration = true;
  21398. auto methodDef = methodInstance->mMethodDef;
  21399. auto typeInstance = methodInstance->GetOwner();
  21400. bool hasNonGenericParams = false;
  21401. bool hasGenericParams = false;
  21402. int dependentGenericStartIdx = 0;
  21403. if (methodDef->mIsLocalMethod)
  21404. {
  21405. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  21406. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  21407. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  21408. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  21409. // over the local method each time
  21410. auto rootMethodInstance = prevMethodState->GetRootMethodState()->mMethodInstance;
  21411. dependentGenericStartIdx = 0;
  21412. if (rootMethodInstance != NULL)
  21413. {
  21414. if (rootMethodInstance->mMethodInfoEx != NULL)
  21415. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  21416. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  21417. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  21418. }
  21419. }
  21420. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodInstance->GetNumGenericArguments(); genericArgIdx++)
  21421. {
  21422. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  21423. if (genericArgType->IsGenericParam())
  21424. {
  21425. hasGenericParams = true;
  21426. auto genericParam = (BfGenericParamType*)genericArgType;
  21427. methodInstance->mIsUnspecialized = true;
  21428. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  21429. methodInstance->mIsUnspecializedVariation = true;
  21430. }
  21431. else
  21432. {
  21433. hasNonGenericParams = true;
  21434. if (genericArgType->IsUnspecializedType())
  21435. {
  21436. methodInstance->mIsUnspecialized = true;
  21437. methodInstance->mIsUnspecializedVariation = true;
  21438. }
  21439. }
  21440. }
  21441. if ((hasGenericParams) && (hasNonGenericParams))
  21442. {
  21443. methodInstance->mIsUnspecializedVariation = true;
  21444. }
  21445. if (typeInstance->IsUnspecializedType())
  21446. {
  21447. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  21448. // actually want to do method processing on it
  21449. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  21450. methodInstance->mIsUnspecializedVariation = true;
  21451. methodInstance->mIsUnspecialized = true;
  21452. }
  21453. if (methodInstance->mIsUnspecializedVariation)
  21454. BF_ASSERT(methodInstance->mIsUnspecialized);
  21455. //TODO: Why did we do this?
  21456. if (methodDef->mMethodType == BfMethodType_Mixin)
  21457. {
  21458. if (methodInstance->IsSpecializedGenericMethod())
  21459. methodInstance->mIsUnspecializedVariation = true;
  21460. methodInstance->mIsUnspecialized = true;
  21461. }
  21462. }
  21463. // methodDeclaration is NULL for default constructors
  21464. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  21465. {
  21466. BF_ASSERT((mCompiler->mCeMachine == NULL) || (!mCompiler->mCeMachine->mDbgPaused));
  21467. BP_ZONE("BfModule::DoMethodDeclaration");
  21468. auto typeInstance = mCurTypeInstance;
  21469. auto typeDef = typeInstance->mTypeDef;
  21470. auto methodDef = mCurMethodInstance->mMethodDef;
  21471. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  21472. // to effectively make mIgnoreWrites method-scoped
  21473. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  21474. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  21475. SetAndRestoreValue<bool> prevAllowLockYield(mContext->mAllowLockYield, false);
  21476. BfTypeState typeState(mCurTypeInstance);
  21477. typeState.mPrevState = mContext->mCurTypeState;
  21478. typeState.mCurMethodDef = methodDef;
  21479. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  21480. BfModule* resolveModule = mContext->mUnreifiedModule;
  21481. if (mCompiler->IsAutocomplete())
  21482. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  21483. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  21484. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  21485. BfMethodState methodState;
  21486. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  21487. methodState.mTempKind = BfMethodState::TempKind_Static;
  21488. defer({ mCurMethodInstance->mHasBeenDeclared = true; });
  21489. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  21490. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  21491. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  21492. // if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  21493. // {
  21494. // BF_ASSERT(mContext->mResolvingVarField);
  21495. // isTemporaryFunc = true;
  21496. // }
  21497. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  21498. FinishInit();
  21499. if (methodDef->mName.StartsWith('_'))
  21500. {
  21501. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  21502. if (methodDef->mName == "__FATALERRORNAME")
  21503. BFMODULE_FATAL(this, "__FATALERRORNAME");
  21504. if (methodDef->mName == "__STACKOVERFLOW")
  21505. StackOverflow();
  21506. if (methodDef->mName == "__INTERNALERROR")
  21507. InternalError("Bad method name", methodDef->GetRefNode());
  21508. }
  21509. if (typeInstance->IsClosure())
  21510. {
  21511. if (methodDef->mName == "Invoke")
  21512. return;
  21513. }
  21514. auto methodInstance = mCurMethodInstance;
  21515. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  21516. addToWorkList = false;
  21517. if (!methodInstance->mHasStartedDeclaration)
  21518. StartMethodDeclaration(methodInstance, prevMethodState.mPrevVal);
  21519. BfAutoComplete* bfAutocomplete = NULL;
  21520. if (mCompiler->mResolvePassData != NULL)
  21521. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  21522. if (methodInstance->mMethodInfoEx != NULL)
  21523. {
  21524. BfTypeInstance* unspecializedTypeInstance = NULL;
  21525. Array<BfTypeReference*> deferredResolveTypes;
  21526. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  21527. {
  21528. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  21529. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  21530. {
  21531. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  21532. }
  21533. else
  21534. {
  21535. auto externConstraintDef = genericParam->GetExternConstraintDef();
  21536. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  21537. auto autoComplete = mCompiler->GetAutoComplete();
  21538. if (autoComplete != NULL)
  21539. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  21540. if (genericParam->mExternType != NULL)
  21541. {
  21542. //
  21543. }
  21544. else
  21545. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  21546. }
  21547. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized, &deferredResolveTypes);
  21548. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  21549. {
  21550. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  21551. if (bfAutocomplete != NULL)
  21552. {
  21553. for (auto nameNode : genericParamDef->mNameNodes)
  21554. {
  21555. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  21556. }
  21557. }
  21558. }
  21559. }
  21560. for (auto typeRef : deferredResolveTypes)
  21561. auto constraintType = ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_None);
  21562. if (methodInstance->mMethodInfoEx != NULL)
  21563. {
  21564. ValidateGenericParams(BfGenericParamKind_Method,
  21565. Span<BfGenericParamInstance*>((BfGenericParamInstance**)methodInstance->mMethodInfoEx->mGenericParams.mVals,
  21566. methodInstance->mMethodInfoEx->mGenericParams.mSize));
  21567. }
  21568. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  21569. AddDependency(genericParam, mCurTypeInstance);
  21570. }
  21571. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  21572. {
  21573. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  21574. BfAstNode* nameNode = methodDeclaration->mNameNode;
  21575. if (nameNode == NULL)
  21576. {
  21577. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  21578. nameNode = ctorDeclaration->mThisToken;
  21579. }
  21580. if ((autoComplete->IsAutocompleteNode(nameNode)) && (autoComplete->mResolveType != BfResolveType_Autocomplete))
  21581. {
  21582. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  21583. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  21584. autoComplete->mDefType = typeDef;
  21585. autoComplete->mDefMethod = methodDef;
  21586. autoComplete->SetDefinitionLocation(nameNode);
  21587. if (methodDef->mIsOverride)
  21588. {
  21589. bool found = false;
  21590. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  21591. {
  21592. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  21593. if (ventry.mDeclaringMethod.mMethodNum == -1)
  21594. continue;
  21595. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  21596. if (virtMethod != NULL)
  21597. {
  21598. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  21599. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  21600. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  21601. {
  21602. // Is matching method
  21603. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  21604. {
  21605. auto baseType = typeInstance->mBaseType;
  21606. if (baseType != NULL)
  21607. {
  21608. found = true;
  21609. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  21610. baseType = baseType->mBaseType;
  21611. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  21612. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  21613. autoComplete->mDefType = baseType->mTypeDef;
  21614. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  21615. }
  21616. }
  21617. break;
  21618. }
  21619. }
  21620. }
  21621. if ((!found) && (autoComplete->mIsGetDefinition) && (methodDef->mDeclaringType->IsExtension()))
  21622. {
  21623. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  21624. {
  21625. auto defaultMethod = methodGroup.mDefault;
  21626. if (defaultMethod == NULL)
  21627. continue;
  21628. if (!defaultMethod->mMethodDef->mIsExtern)
  21629. continue;
  21630. if (!CompareMethodSignatures(defaultMethod, methodInstance))
  21631. continue;
  21632. autoComplete->SetDefinitionLocation(defaultMethod->mMethodDef->GetRefNode(), true);
  21633. autoComplete->mDefType = typeInstance->mTypeDef;
  21634. autoComplete->mDefMethod = defaultMethod->mMethodDef;
  21635. }
  21636. }
  21637. }
  21638. }
  21639. }
  21640. bool reportErrors = true;
  21641. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  21642. reportErrors = true;
  21643. // Only the defining contexts needs to report errors here
  21644. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  21645. if (methodDef->mMethodType == BfMethodType_Dtor)
  21646. {
  21647. if (methodDef->mIsStatic)
  21648. {
  21649. }
  21650. else
  21651. {
  21652. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  21653. {
  21654. BfAstNode* refNode = methodDeclaration;
  21655. if (refNode == NULL)
  21656. {
  21657. // Whatever caused this ctor to be generated should have caused another failure
  21658. // But that failure might not be generated until the ctor is generated
  21659. }
  21660. else
  21661. {
  21662. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  21663. if (dtorDecl != NULL)
  21664. refNode = dtorDecl->mThisToken;
  21665. Fail("Structs cannot have destructors", refNode);
  21666. }
  21667. }
  21668. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21669. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  21670. (mCurTypeInstance != mContext->mBfObjectType))
  21671. {
  21672. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  21673. }
  21674. }
  21675. }
  21676. BfType* resolvedReturnType = NULL;
  21677. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  21678. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  21679. (methodDef->mReturnTypeRef != NULL))
  21680. {
  21681. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  21682. if (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>())
  21683. {
  21684. // An invalid 'var' error would not have been caught in the original property type pass
  21685. mIgnoreErrors = false;
  21686. }
  21687. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_NoReify);
  21688. if ((((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0) || (methodInstance->mIsAutocompleteMethod))
  21689. && (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>()))
  21690. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  21691. else
  21692. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration, flags);
  21693. if (resolvedReturnType == NULL)
  21694. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  21695. if ((methodDef->mIsReadOnly) && (!resolvedReturnType->IsRef()))
  21696. {
  21697. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration))
  21698. if (methodDeclaration->mReadOnlySpecifier != NULL)
  21699. Fail("Readonly specifier is only valid on 'ref' return types", methodDeclaration->mReadOnlySpecifier);
  21700. }
  21701. }
  21702. else
  21703. {
  21704. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  21705. }
  21706. BF_ASSERT(resolvedReturnType != NULL);
  21707. mCurMethodInstance->mReturnType = resolvedReturnType;
  21708. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  21709. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  21710. //if (!methodInstance->IsSpecializedGenericMethod())
  21711. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21712. if (methodDef->mExplicitInterface != NULL)
  21713. {
  21714. auto autoComplete = mCompiler->GetAutoComplete();
  21715. if (autoComplete != NULL)
  21716. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  21717. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  21718. BfTypeInstance* explicitInterface = NULL;
  21719. if (explicitType != NULL)
  21720. explicitInterface = explicitType->ToTypeInstance();
  21721. if (explicitInterface != NULL)
  21722. {
  21723. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  21724. if (autoComplete != NULL)
  21725. {
  21726. BfTokenNode* dotToken = NULL;
  21727. BfAstNode* nameNode = NULL;
  21728. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  21729. {
  21730. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  21731. nameNode = methodDeclaration->mNameNode;
  21732. }
  21733. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  21734. }
  21735. }
  21736. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  21737. {
  21738. bool interfaceFound = false;
  21739. for (auto ifaceInst : typeInstance->mInterfaces)
  21740. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  21741. if ((!interfaceFound) && (!typeInstance->mTypeFailed))
  21742. {
  21743. if (methodDef->mMethodDeclaration != NULL)
  21744. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  21745. else
  21746. {
  21747. // For property decls, we should have already given the error during type population
  21748. if (mCompiler->mRevision == 1)
  21749. AssertErrorState();
  21750. }
  21751. }
  21752. }
  21753. }
  21754. bool isThisStruct = mCurTypeInstance->IsStruct();
  21755. BfType* thisType = NULL;
  21756. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  21757. {
  21758. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  21759. {
  21760. thisType = mCurTypeInstance;
  21761. if (thisType == NULL)
  21762. return;
  21763. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  21764. {
  21765. BfTypeUtils::SplatIterate([&](BfType* checkType)
  21766. {
  21767. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  21768. }, thisType);
  21769. }
  21770. }
  21771. else
  21772. {
  21773. thisType = mCurTypeInstance;
  21774. resolveModule->PopulateType(thisType, BfPopulateType_Declaration);
  21775. }
  21776. }
  21777. int implicitParamCount = 0;
  21778. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  21779. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  21780. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  21781. bool hadDelegateParams = false;
  21782. bool hadParams = false;
  21783. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  21784. {
  21785. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  21786. BfParameterDef* paramDef = NULL;
  21787. int paramDefIdx = -1;
  21788. if (paramIdx < implicitParamCount)
  21789. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  21790. else
  21791. {
  21792. paramDefIdx = paramIdx - implicitParamCount;
  21793. paramDef = methodDef->mParams[paramDefIdx];
  21794. }
  21795. if (hadParams)
  21796. break;
  21797. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  21798. continue;
  21799. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  21800. (paramDef->mParamKind != BfParamKind_AppendIdx))
  21801. {
  21802. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  21803. if (mCompiler->mResolvePassData->mAutoComplete->IsAutocompleteNode(paramDef->mTypeRef))
  21804. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("token", "in"), paramDef->mTypeRef->ToString());
  21805. }
  21806. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  21807. {
  21808. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  21809. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  21810. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  21811. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  21812. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  21813. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  21814. }
  21815. BfType* resolvedParamType = NULL;
  21816. if (closureCaptureEntry != NULL)
  21817. resolvedParamType = closureCaptureEntry->mType;
  21818. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfLetTypeReference>()))
  21819. {
  21820. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  21821. resolvedParamType = mContext->mBfObjectType;
  21822. }
  21823. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfVarTypeReference>()))
  21824. {
  21825. if (methodDef->mMethodType != BfMethodType_Mixin)
  21826. {
  21827. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  21828. resolvedParamType = mContext->mBfObjectType;
  21829. }
  21830. else
  21831. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21832. }
  21833. BfType* unresolvedParamType = resolvedParamType;
  21834. bool wasGenericParam = false;
  21835. if (resolvedParamType == NULL)
  21836. {
  21837. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue | BfResolveTypeRefFlag_NoReify);
  21838. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  21839. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  21840. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  21841. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  21842. resolvedParamType = resolvedParamType->GetUnderlyingType();
  21843. }
  21844. if (resolvedParamType == NULL)
  21845. {
  21846. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21847. unresolvedParamType = resolvedParamType;
  21848. if (mCurTypeInstance->IsBoxed())
  21849. {
  21850. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  21851. // If we failed a lookup here then we better have also failed it in the original type
  21852. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.ContainsKey(boxedType->mElementType->ToTypeInstance()));
  21853. }
  21854. }
  21855. BF_ASSERT(!resolvedParamType->IsDeleting());
  21856. if (!methodInstance->IsSpecializedGenericMethod())
  21857. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21858. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  21859. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  21860. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  21861. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  21862. {
  21863. if (paramDef->mParamKind == BfParamKind_Params)
  21864. {
  21865. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  21866. if (refNode != NULL)
  21867. refNode = paramDef->mParamDeclaration->mModToken;
  21868. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  21869. }
  21870. BfTypedValue defaultValue;
  21871. if (resolvedParamType->IsConstExprValue())
  21872. {
  21873. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  21874. BfExprEvaluator exprEvaluator(this);
  21875. exprEvaluator.mExpectingType = constExprType->mType;
  21876. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  21877. defaultValue = exprEvaluator.GetResult();
  21878. }
  21879. else
  21880. {
  21881. BfTypeState typeState;
  21882. typeState.mType = mCurTypeInstance;
  21883. typeState.mCurTypeDef = methodDef->mDeclaringType;
  21884. //typeState.mCurMethodDef = methodDef;
  21885. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  21886. BfConstResolver constResolver(this);
  21887. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  21888. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  21889. {
  21890. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  21891. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  21892. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  21893. {
  21894. defaultValue = castedDefaultValue; // Good!
  21895. }
  21896. else if (!CanCast(defaultValue, resolvedParamType))
  21897. {
  21898. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  21899. // a conversion operator.
  21900. // This should throw an error
  21901. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  21902. AssertErrorState();
  21903. if (!defaultValue.mValue.IsConst())
  21904. defaultValue = BfTypedValue();
  21905. }
  21906. }
  21907. }
  21908. if (!defaultValue)
  21909. {
  21910. defaultValue = GetDefaultTypedValue(resolvedParamType);
  21911. if (!defaultValue.mValue.IsConst())
  21912. defaultValue = BfTypedValue();
  21913. }
  21914. if (defaultValue)
  21915. {
  21916. if (defaultValue.mType->IsVar())
  21917. {
  21918. AssertErrorState();
  21919. }
  21920. else
  21921. {
  21922. BF_ASSERT(defaultValue.mValue.IsConst());
  21923. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  21924. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  21925. CurrentAddToConstHolder(defaultValue.mValue);
  21926. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  21927. }
  21928. }
  21929. }
  21930. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  21931. {
  21932. bool addParams = true;
  21933. bool isValid = false;
  21934. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  21935. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->IsInstanceOf(mCompiler->mSpanTypeDef)))
  21936. {
  21937. // Span<T>
  21938. isValid = true;
  21939. }
  21940. else if (resolvedParamType->IsArray())
  21941. {
  21942. // Array is the 'normal' params type
  21943. isValid = true;
  21944. }
  21945. else if (resolvedParamType->IsSizedArray())
  21946. {
  21947. isValid = true;
  21948. }
  21949. else if (resolvedParamType->IsVar())
  21950. {
  21951. isValid = true;
  21952. }
  21953. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()) || (resolvedParamType->IsMethodRef()))
  21954. {
  21955. hadDelegateParams = true;
  21956. // This means we copy the params from a delegate
  21957. BfMethodParam methodParam;
  21958. methodParam.mResolvedType = resolvedParamType;
  21959. methodParam.mParamDefIdx = paramDefIdx;
  21960. methodParam.mDelegateParamIdx = 0;
  21961. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21962. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  21963. {
  21964. methodParam.mDelegateParamIdx = delegateParamIdx;
  21965. mCurMethodInstance->mParams.Add(methodParam);
  21966. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  21967. if (!methodInstance->IsSpecializedGenericMethod())
  21968. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21969. }
  21970. isValid = true;
  21971. addParams = false;
  21972. }
  21973. else if (resolvedParamType->IsTuple())
  21974. {
  21975. auto tupleType = (BfTupleType*)resolvedParamType;
  21976. PopulateType(tupleType);
  21977. hadDelegateParams = true;
  21978. // This means we copy the params from a delegate
  21979. BfMethodParam methodParam;
  21980. methodParam.mResolvedType = resolvedParamType;
  21981. methodParam.mParamDefIdx = paramDefIdx;
  21982. methodParam.mDelegateParamIdx = 0;
  21983. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21984. for (int delegateParamIdx = 0; delegateParamIdx < tupleType->mFieldInstances.mSize; delegateParamIdx++)
  21985. {
  21986. auto& fieldInstance = tupleType->mFieldInstances[delegateParamIdx];
  21987. methodParam.mDelegateParamIdx = delegateParamIdx;
  21988. mCurMethodInstance->mParams.Add(methodParam);
  21989. if (!methodInstance->IsSpecializedGenericMethod())
  21990. AddDependency(fieldInstance.mResolvedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21991. }
  21992. isValid = true;
  21993. addParams = false;
  21994. }
  21995. else if (resolvedParamType->IsGenericParam())
  21996. {
  21997. bool isGenericDelegateParams = false;
  21998. bool addDelegateParamsType = false;
  21999. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType, false, BfFailHandleKind_Ignore);
  22000. if (genericParamInstance == NULL)
  22001. {
  22002. // Delegate case with a 'params T'?
  22003. isGenericDelegateParams = true;
  22004. addDelegateParamsType = true;
  22005. }
  22006. else if (genericParamInstance->mTypeConstraint != NULL)
  22007. {
  22008. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  22009. if ((genericParamInstance->mTypeConstraint->IsArray()) || (genericParamInstance->mTypeConstraint->IsSizedArray()))
  22010. {
  22011. BfMethodParam methodParam;
  22012. methodParam.mResolvedType = resolvedParamType;
  22013. methodParam.mParamDefIdx = paramDefIdx;
  22014. mCurMethodInstance->mParams.Add(methodParam);
  22015. isValid = true;
  22016. }
  22017. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) || (genericParamInstance->mTypeConstraint->IsTuple()) ||
  22018. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  22019. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mTupleTypeDef)))))
  22020. {
  22021. isGenericDelegateParams = true;
  22022. //addDelegateParamsType = typeInstConstraint->IsInstanceOf(mCompiler->mTupleTypeDef);
  22023. addDelegateParamsType = true;
  22024. }
  22025. }
  22026. if (isGenericDelegateParams)
  22027. {
  22028. mCurMethodInstance->mHadGenericDelegateParams = true;
  22029. isValid = true;
  22030. addParams = false;
  22031. if (addDelegateParamsType)
  22032. {
  22033. BfMethodParam methodParam;
  22034. methodParam.mResolvedType = CreateModifiedTypeType(resolvedParamType, BfToken_Params);
  22035. methodParam.mParamDefIdx = paramDefIdx;
  22036. mCurMethodInstance->mParams.Add(methodParam);
  22037. //TODO: Why do we have this 'if'
  22038. if (!methodInstance->IsSpecializedGenericMethod())
  22039. AddDependency(methodParam.mResolvedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  22040. }
  22041. }
  22042. }
  22043. else
  22044. {
  22045. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  22046. if ((paramTypeInst != NULL) &&
  22047. ((paramTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mTupleTypeDef))))
  22048. {
  22049. // If we have a 'params T' and 'T' gets specialized with actually 'Tuple', 'Delegate' or 'Function' then just ignore it
  22050. isValid = true;
  22051. addParams = false;
  22052. }
  22053. }
  22054. if (!isValid)
  22055. {
  22056. Fail("Parameters with 'params' specifiers can only be used for array, span, tuple, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  22057. // Failure case, make it an Object[]
  22058. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  22059. }
  22060. if ((addParams) && (resolvedParamType != NULL))
  22061. {
  22062. BfMethodParam methodParam;
  22063. methodParam.mResolvedType = resolvedParamType;
  22064. methodParam.mParamDefIdx = paramDefIdx;
  22065. mCurMethodInstance->mParams.push_back(methodParam);
  22066. }
  22067. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  22068. {
  22069. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  22070. }
  22071. }
  22072. else
  22073. {
  22074. BfMethodParam methodParam;
  22075. methodParam.mResolvedType = resolvedParamType;
  22076. methodParam.mParamDefIdx = paramDefIdx;
  22077. mCurMethodInstance->mParams.Add(methodParam);
  22078. }
  22079. }
  22080. if (hadDelegateParams)
  22081. {
  22082. HashSet<String> usedNames;
  22083. Dictionary<int, int> usedParamDefIdx;
  22084. for (auto methodParam : methodDef->mParams)
  22085. {
  22086. usedNames.Add(methodParam->mName);
  22087. }
  22088. for (auto& methodParam : mCurMethodInstance->mParams)
  22089. {
  22090. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  22091. {
  22092. int* refCount = NULL;
  22093. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  22094. (*refCount)++;
  22095. }
  22096. }
  22097. for (auto& methodParam : mCurMethodInstance->mParams)
  22098. {
  22099. if (methodParam.mDelegateParamIdx != -1)
  22100. {
  22101. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  22102. methodParam.mDelegateParamNameCombine = true;
  22103. if (methodParam.mResolvedType->IsTuple())
  22104. {
  22105. auto tupleType = (BfTupleType*)methodParam.mResolvedType;
  22106. auto& fieldInstance = tupleType->mFieldInstances[methodParam.mDelegateParamIdx];
  22107. auto paramName = fieldInstance.GetFieldDef()->mName;
  22108. if ((!usedNames.Add(paramName)) || (::isdigit((uint8)paramName[0])))
  22109. methodParam.mDelegateParamNameCombine = true;
  22110. }
  22111. else
  22112. {
  22113. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  22114. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  22115. if (!usedNames.Add(paramName))
  22116. methodParam.mDelegateParamNameCombine = true;
  22117. }
  22118. }
  22119. }
  22120. }
  22121. int argIdx = 0;
  22122. resolveModule->PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  22123. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  22124. {
  22125. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  22126. auto thisType = methodInstance->GetOwner();
  22127. if (methodInstance->GetParamIsSplat(thisIdx))
  22128. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  22129. else if (!thisType->IsValuelessType())
  22130. {
  22131. BfTypeCode loweredTypeCode = BfTypeCode_None;
  22132. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  22133. if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (!methodInstance->ForcingThisPtr()))
  22134. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  22135. argIdx++;
  22136. if (loweredTypeCode2 != BfTypeCode_None)
  22137. argIdx++;
  22138. }
  22139. }
  22140. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  22141. argIdx++;
  22142. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  22143. {
  22144. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  22145. BfType* checkType = methodParam.mResolvedType;
  22146. int checkArgIdx = argIdx;
  22147. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  22148. {
  22149. checkArgIdx = 0;
  22150. checkType = methodInstance->GetThisType();
  22151. }
  22152. if (checkType->IsMethodRef())
  22153. {
  22154. methodParam.mIsSplat = true;
  22155. }
  22156. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting(paramIdx)))
  22157. {
  22158. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  22159. if (checkType->IsSplattable())
  22160. {
  22161. bool isSplat = false;
  22162. auto checkTypeInstance = checkType->ToTypeInstance();
  22163. if ((checkTypeInstance != NULL) && (checkTypeInstance->mIsCRepr))
  22164. isSplat = true;
  22165. int splatCount = checkType->GetSplatCount();
  22166. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  22167. isSplat = true;
  22168. if (isSplat)
  22169. {
  22170. methodParam.mIsSplat = true;
  22171. argIdx += splatCount;
  22172. continue;
  22173. }
  22174. }
  22175. else if (!checkType->IsValuelessType())
  22176. {
  22177. BfTypeCode loweredTypeCode = BfTypeCode_None;
  22178. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  22179. if (!mIsComptimeModule)
  22180. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  22181. argIdx++;
  22182. if (loweredTypeCode2 != BfTypeCode_None)
  22183. argIdx++;
  22184. continue;
  22185. }
  22186. }
  22187. argIdx++;
  22188. }
  22189. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  22190. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  22191. {
  22192. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  22193. }
  22194. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  22195. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  22196. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  22197. (!methodDef->mIsSkipCall))
  22198. {
  22199. if (methodDeclaration->mEndSemicolon == NULL)
  22200. {
  22201. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  22202. {
  22203. //
  22204. }
  22205. else
  22206. AssertParseErrorState();
  22207. }
  22208. else
  22209. {
  22210. bool isError = true;
  22211. if (typeInstance->IsTypedPrimitive())
  22212. {
  22213. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  22214. {
  22215. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  22216. {
  22217. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  22218. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  22219. {
  22220. isError = false;
  22221. }
  22222. else if (mCurTypeInstance->IsEnum())
  22223. {
  22224. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0)->IsInteger())) ||
  22225. ((methodInstance->mReturnType->IsInteger()) && (methodInstance->GetParamType(0) == typeInstance)))
  22226. {
  22227. isError = false;
  22228. }
  22229. }
  22230. }
  22231. }
  22232. }
  22233. if (isError)
  22234. {
  22235. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  22236. MethodToString(methodInstance).c_str()),
  22237. methodDef->GetRefNode());
  22238. }
  22239. }
  22240. }
  22241. if (methodDef->IsEmptyPartial())
  22242. hasExternSpecifier = true;
  22243. if (!methodInstance->IsAutocompleteMethod())
  22244. {
  22245. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  22246. int implicitParamCount = methodInstance->GetImplicitParamCount();
  22247. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  22248. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  22249. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  22250. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  22251. int paramIdx = 0;
  22252. int defaultParamIdx = 0;
  22253. while (true)
  22254. {
  22255. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  22256. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  22257. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  22258. {
  22259. paramIdx++;
  22260. continue;
  22261. }
  22262. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  22263. {
  22264. defaultParamIdx++;
  22265. continue;
  22266. }
  22267. if ((isDone) || (isDefaultDone))
  22268. {
  22269. // 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
  22270. // to cause us to throw an assertion in the declaration here
  22271. if ((!defaultMethodInstance->mHadGenericDelegateParams) && (!methodInstance->mHasFailed) && (!defaultMethodInstance->mHasFailed))
  22272. BF_ASSERT((isDone) && (isDefaultDone));
  22273. break;
  22274. }
  22275. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  22276. if (paramType->IsRef())
  22277. paramType = paramType->GetUnderlyingType();
  22278. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  22279. paramIdx++;
  22280. defaultParamIdx++;
  22281. }
  22282. }
  22283. StringT<4096> mangledName;
  22284. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  22285. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  22286. {
  22287. auto paramType = methodInstance->GetParamType(paramIdx);
  22288. if (paramType->IsComposite())
  22289. resolveModule->PopulateType(paramType, BfPopulateType_Data);
  22290. if (!methodInstance->IsParamSkipped(paramIdx))
  22291. {
  22292. if (paramType->IsStruct())
  22293. {
  22294. //
  22295. }
  22296. else
  22297. {
  22298. PopulateType(paramType, BfPopulateType_Declaration);
  22299. }
  22300. }
  22301. }
  22302. // Only process method in default unspecialized mode, not in variations
  22303. if (methodInstance->mIsUnspecializedVariation)
  22304. return;
  22305. resolveModule->PopulateType(resolvedReturnType, BfPopulateType_Data);
  22306. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  22307. if (resolvedReturnType->IsValuelessType())
  22308. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  22309. if (!mBfIRBuilder->mIgnoreWrites)
  22310. {
  22311. bool isIntrinsic = false;
  22312. if (!methodInstance->mIRFunction)
  22313. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  22314. if (isIntrinsic)
  22315. {
  22316. addToWorkList = false;
  22317. }
  22318. }
  22319. else
  22320. {
  22321. GetMethodCustomAttributes(methodInstance);
  22322. }
  22323. auto func = methodInstance->mIRFunction;
  22324. // if (methodInstance->mIsReified)
  22325. // CheckHotMethod(methodInstance, mangledName);
  22326. for (auto& param : methodInstance->mParams)
  22327. {
  22328. BF_ASSERT(!param.mResolvedType->IsDeleting());
  22329. }
  22330. 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);
  22331. SizedArray<BfIRMDNode, 8> diParams;
  22332. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  22333. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  22334. {
  22335. //CS0708
  22336. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  22337. }
  22338. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  22339. {
  22340. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  22341. methodDef->mIsVirtual = false;
  22342. }
  22343. BfAstNode* mutSpecifier = NULL;
  22344. if (methodDeclaration != NULL)
  22345. mutSpecifier = methodDeclaration->mMutSpecifier;
  22346. else if (methodDef->GetPropertyMethodDeclaration() != NULL)
  22347. {
  22348. mutSpecifier = methodDef->GetPropertyMethodDeclaration()->mMutSpecifier;
  22349. if (mutSpecifier == NULL)
  22350. {
  22351. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22352. if (propertyDeclaration != NULL)
  22353. {
  22354. if (auto propExprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  22355. mutSpecifier = propExprBody->mMutSpecifier;
  22356. }
  22357. }
  22358. }
  22359. if ((mutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  22360. {
  22361. if (methodDef->mIsStatic)
  22362. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", mutSpecifier);
  22363. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  22364. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", mutSpecifier);
  22365. else if (methodDef->mMethodType == BfMethodType_Ctor)
  22366. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", mutSpecifier);
  22367. else if (methodDef->mMethodType == BfMethodType_Dtor)
  22368. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", mutSpecifier);
  22369. }
  22370. if (isTemporaryFunc)
  22371. {
  22372. // This handles temporary methods for autocomplete types
  22373. //BF_ASSERT(mIsScratchModule);
  22374. //BF_ASSERT(mCompiler->IsAutocomplete());
  22375. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  22376. return; // Bail out early for autocomplete pass
  22377. }
  22378. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  22379. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  22380. // autocompleter. Why did we have this check anyway?
  22381. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  22382. {
  22383. AddMethodReference(methodInstance);
  22384. mFuncReferences[methodInstance] = func;
  22385. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  22386. }*/
  22387. if (mParentModule != NULL)
  22388. {
  22389. // For extension modules we need to keep track of our own methods so we can know which methods
  22390. // we have defined ourselves and which are from the parent module or other extensions
  22391. if (!func.IsFake())
  22392. {
  22393. if (func)
  22394. mFuncReferences[methodInstance] = func;
  22395. }
  22396. }
  22397. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  22398. {
  22399. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  22400. auto owningModule = methodInstance->GetOwner()->mModule;
  22401. if (!owningModule->mIsScratchModule)
  22402. owningModule->mOnDemandMethodCount++;
  22403. VerifyOnDemandMethods();
  22404. }
  22405. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  22406. if (wasAwaitingDecl)
  22407. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  22408. if (addToWorkList)
  22409. {
  22410. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  22411. {
  22412. AddMethodToWorkList(methodInstance);
  22413. }
  22414. else
  22415. {
  22416. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  22417. methodInstance->mIgnoreBody = true;
  22418. if (typeInstance->IsUnspecializedType())
  22419. {
  22420. // Don't hold on to actual Function for unspecialized types
  22421. methodInstance->mIRFunction = BfIRFunction();
  22422. }
  22423. }
  22424. }
  22425. else
  22426. {
  22427. //BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  22428. }
  22429. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  22430. (!methodDef->mIsLocalMethod) &&
  22431. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  22432. (!methodDef->mReturnTypeRef->IsTemporary()))
  22433. {
  22434. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  22435. {
  22436. //TODO:
  22437. //CS0053
  22438. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  22439. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  22440. methodDef->mReturnTypeRef, true);
  22441. }
  22442. else
  22443. {
  22444. //CS0050
  22445. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  22446. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  22447. methodDef->mReturnTypeRef, true);
  22448. }
  22449. }
  22450. if (typeInstance->IsInterface())
  22451. {
  22452. if (methodDef->mMethodType == BfMethodType_Ctor)
  22453. Fail("Interfaces cannot contain constructors", methodDeclaration);
  22454. if (methodDeclaration != NULL)
  22455. {
  22456. if (methodDef->mBody == NULL)
  22457. {
  22458. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  22459. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  22460. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  22461. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  22462. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  22463. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  22464. }
  22465. }
  22466. }
  22467. bool foundHiddenMethod = false;
  22468. BfTokenNode* virtualToken = NULL;
  22469. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22470. if (propertyDeclaration != NULL)
  22471. virtualToken = propertyDeclaration->mVirtualSpecifier;
  22472. else if (methodDeclaration != NULL)
  22473. virtualToken = methodDeclaration->mVirtualSpecifier;
  22474. // Don't compare specialized generic methods against normal methods
  22475. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  22476. (!methodDef->mIsLocalMethod) && (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  22477. {
  22478. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  22479. {
  22480. typeDef->PopulateMemberSets();
  22481. BfMethodDef* nextMethod = NULL;
  22482. BfMemberSetEntry* entry = NULL;
  22483. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22484. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22485. while (nextMethod != NULL)
  22486. {
  22487. auto checkMethod = nextMethod;
  22488. nextMethod = nextMethod->mNextWithSameName;
  22489. if (checkMethod == methodDef)
  22490. continue;
  22491. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22492. if (checkMethodInstance == NULL)
  22493. {
  22494. if (methodDef->mDeclaringType->IsExtension())
  22495. checkMethodInstance = GetRawMethodInstanceAtIdx(typeInstance, checkMethod->mIdx);
  22496. if (checkMethodInstance == NULL)
  22497. continue;
  22498. }
  22499. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  22500. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  22501. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  22502. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  22503. {
  22504. bool canChain = false;
  22505. if ((methodDef->mParams.empty()) &&
  22506. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  22507. {
  22508. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  22509. canChain = true;
  22510. else if (methodDef->mMethodType == BfMethodType_Normal)
  22511. {
  22512. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  22513. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  22514. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  22515. canChain = true;
  22516. }
  22517. }
  22518. if (canChain)
  22519. {
  22520. bool isBetter;
  22521. bool isWorse;
  22522. CompareDeclTypes(typeInstance, checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  22523. if (isBetter && !isWorse)
  22524. {
  22525. methodInstance->mChainType = BfMethodChainType_ChainHead;
  22526. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  22527. }
  22528. else
  22529. {
  22530. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  22531. methodInstance->mChainType = BfMethodChainType_ChainMember;
  22532. }
  22533. }
  22534. else
  22535. {
  22536. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  22537. continue;
  22538. bool silentlyAllow = false;
  22539. bool extensionWarn = false;
  22540. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  22541. {
  22542. if (typeInstance->IsInterface())
  22543. {
  22544. if (methodDef->mIsOverride)
  22545. silentlyAllow = true;
  22546. }
  22547. else
  22548. {
  22549. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  22550. {
  22551. silentlyAllow = true;
  22552. methodInstance->mIsInnerOverride = true;
  22553. CheckOverridenMethod(methodInstance, checkMethodInstance);
  22554. }
  22555. else if (!checkMethod->mDeclaringType->IsExtension())
  22556. {
  22557. foundHiddenMethod = true;
  22558. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  22559. silentlyAllow = true;
  22560. else if (methodDef->mIsNew)
  22561. {
  22562. silentlyAllow = true;
  22563. }
  22564. else if (checkMethod->GetMethodDeclaration() == NULL)
  22565. silentlyAllow = true;
  22566. else if (methodDef->mIsOverride)
  22567. silentlyAllow = true;
  22568. else
  22569. extensionWarn = true;
  22570. }
  22571. else
  22572. silentlyAllow = true;
  22573. }
  22574. }
  22575. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  22576. silentlyAllow = true;
  22577. if (checkMethod->mMethodDeclaration == NULL)
  22578. {
  22579. // This can allow emission of a default ctor if we've already auto-added a default ctor
  22580. silentlyAllow = true;
  22581. }
  22582. if (checkMethod->mMethodType == BfMethodType_CtorCalcAppend)
  22583. {
  22584. // Only use the main ctor as the error method
  22585. silentlyAllow = true;
  22586. }
  22587. if (!silentlyAllow)
  22588. {
  22589. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  22590. {
  22591. auto refNode = methodDef->GetRefNode();
  22592. BfError* bfError;
  22593. if (extensionWarn)
  22594. {
  22595. if (methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject)
  22596. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  22597. 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'.",
  22598. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  22599. else
  22600. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  22601. "This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional.", refNode);
  22602. }
  22603. else
  22604. {
  22605. bfError = Fail(StrFormat("Method '%s' already declared with the same parameter types", MethodToString(checkMethodInstance).c_str()), refNode, true);
  22606. }
  22607. if ((bfError != NULL) && (checkMethod->GetRefNode() != refNode))
  22608. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  22609. }
  22610. }
  22611. }
  22612. }
  22613. }
  22614. }
  22615. // Virtual methods give their error while slotting
  22616. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  22617. (!methodDef->mIsLocalMethod) &&
  22618. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  22619. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  22620. {
  22621. auto baseType = typeInstance->mBaseType;
  22622. while (baseType != NULL)
  22623. {
  22624. auto baseTypeDef = baseType->mTypeDef;
  22625. baseTypeDef->PopulateMemberSets();
  22626. BfMethodDef* checkMethod = NULL;
  22627. BfMemberSetEntry* entry = NULL;
  22628. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22629. checkMethod = (BfMethodDef*)entry->mMemberDef;
  22630. while (checkMethod != NULL)
  22631. {
  22632. if (checkMethod->mMethodDeclaration == NULL)
  22633. {
  22634. checkMethod = checkMethod->mNextWithSameName;
  22635. continue;
  22636. }
  22637. if (baseType->mMethodInstanceGroups.size() == 0)
  22638. {
  22639. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  22640. break;
  22641. }
  22642. if (checkMethod == methodDef)
  22643. {
  22644. checkMethod = checkMethod->mNextWithSameName;
  22645. continue;
  22646. }
  22647. if (checkMethod->mName != methodDef->mName)
  22648. {
  22649. checkMethod = checkMethod->mNextWithSameName;
  22650. continue;
  22651. }
  22652. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  22653. if (checkMethodInstance != NULL)
  22654. {
  22655. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  22656. (checkMethod->mProtection != BfProtection_Private) &&
  22657. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  22658. {
  22659. if ((!methodDef->mIsNew) && (!checkMethod->mDeclaringType->IsExtension()))
  22660. {
  22661. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  22662. if (refNode != NULL)
  22663. {
  22664. 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?
  22665. if (bfError != NULL)
  22666. {
  22667. bfError->mIsPersistent = true;
  22668. mCompiler->mPassInstance->MoreInfo("See inherited method", checkMethod->GetRefNode());
  22669. }
  22670. }
  22671. }
  22672. foundHiddenMethod = true;
  22673. break;
  22674. }
  22675. }
  22676. checkMethod = checkMethod->mNextWithSameName;
  22677. }
  22678. if (foundHiddenMethod)
  22679. break;
  22680. baseType = baseType->mBaseType;
  22681. }
  22682. if ((methodDef->mIsNew) && (!foundHiddenMethod) && (!mCurTypeInstance->IsSpecializedType()))
  22683. {
  22684. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22685. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  22686. methodDeclaration->mNewSpecifier;
  22687. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  22688. }
  22689. }
  22690. }
  22691. if ((methodDef->mIsConcrete) && (!methodInstance->mIsForeignMethodDef) && (!mCurTypeInstance->IsInterface()))
  22692. {
  22693. Fail("Only interfaces methods can be declared as 'concrete'", methodDeclaration->mVirtualSpecifier);
  22694. }
  22695. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic) && (!methodInstance->mIsInnerOverride))
  22696. {
  22697. if ((virtualToken != NULL) && (virtualToken->mToken == BfToken_Override) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  22698. Fail("No suitable method found to override", virtualToken, true);
  22699. else
  22700. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  22701. }
  22702. else if (methodDef->mIsVirtual)
  22703. {
  22704. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  22705. Fail("Virtual or abstract members cannot be 'private'", virtualToken, true);
  22706. if ((methodDef->mProtection == BfProtection_Internal) && (virtualToken != NULL))
  22707. Fail("Virtual or abstract members cannot be 'internal'. Consider using the 'protected internal' access specifier.", virtualToken, true);
  22708. }
  22709. mCompiler->mStats.mMethodDeclarations++;
  22710. mCompiler->UpdateCompletion();
  22711. }
  22712. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  22713. {
  22714. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  22715. auto typeInstance = mCurTypeInstance;
  22716. auto methodDef = methodInstance->mMethodDef;
  22717. int virtualMethodMatchIdx = -1;
  22718. if (typeInstance->mHotTypeData != NULL)
  22719. {
  22720. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  22721. {
  22722. BF_ASSERT(mCompiler->IsHotCompile());
  22723. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  22724. // may slot this override anyway (?)
  22725. int vTableStart = 0;
  22726. auto implBaseType = typeInstance->GetImplBaseType();
  22727. if (implBaseType != NULL)
  22728. vTableStart = implBaseType->mVirtualMethodTableSize;
  22729. StringT<512> mangledName;
  22730. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  22731. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  22732. {
  22733. // O(1) checking when virtual methods haven't changed
  22734. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  22735. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  22736. if (mangledName == entry.mFuncName)
  22737. {
  22738. virtualMethodMatchIdx = vTableStart + checkIdx;
  22739. break;
  22740. }
  22741. }
  22742. if (virtualMethodMatchIdx != -1)
  22743. {
  22744. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22745. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  22746. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  22747. }
  22748. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  22749. }
  22750. }
  22751. if (virtualMethodMatchIdx == -1)
  22752. {
  22753. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  22754. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  22755. typeInstance->mVirtualMethodTable.push_back(entry);
  22756. }
  22757. }
  22758. void BfModule::CompareDeclTypes(BfTypeInstance* typeInst, BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  22759. {
  22760. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  22761. {
  22762. // When we provide an extension override in the same project a root type override
  22763. isBetter = true;
  22764. isWorse = false;
  22765. }
  22766. else
  22767. {
  22768. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22769. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22770. }
  22771. if ((isBetter == isWorse) && (typeInst != NULL) && (newDeclType->IsExtension()) && (prevDeclType->IsExtension()))
  22772. {
  22773. if ((typeInst->mGenericTypeInfo != NULL) && (typeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL))
  22774. {
  22775. isBetter = false;
  22776. isWorse = false;
  22777. auto newConstraints = typeInst->GetGenericParamsVector(newDeclType);
  22778. auto prevConstraints = typeInst->GetGenericParamsVector(prevDeclType);
  22779. for (int genericIdx = 0; genericIdx < (int)newConstraints->size(); genericIdx++)
  22780. {
  22781. auto newConstraint = (*newConstraints)[genericIdx];
  22782. auto prevConstraint = (*prevConstraints)[genericIdx];
  22783. bool newIsSubset = AreConstraintsSubset(newConstraint, prevConstraint);
  22784. bool prevIsSubset = AreConstraintsSubset(prevConstraint, newConstraint);
  22785. if ((prevIsSubset) && (!newIsSubset))
  22786. isBetter = true;
  22787. if ((!prevIsSubset) && (newIsSubset))
  22788. isWorse = true;
  22789. }
  22790. }
  22791. }
  22792. }
  22793. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  22794. {
  22795. BP_ZONE("BfModule::SlotVirtualMethod");
  22796. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  22797. return false;
  22798. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  22799. {
  22800. if (!mCompiler->mOptions.mAllowHotSwapping)
  22801. return;
  22802. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  22803. return;
  22804. if (methodInstance->mHotMethod == NULL)
  22805. CheckHotMethod(methodInstance, "");
  22806. if (methodInstance->mHotMethod == NULL)
  22807. return;
  22808. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  22809. if (declMethodInstance->mHotMethod == NULL)
  22810. CheckHotMethod(declMethodInstance, "");
  22811. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  22812. virtualDecl->mRefCount++;
  22813. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  22814. };
  22815. auto typeInstance = mCurTypeInstance;
  22816. auto typeDef = typeInstance->mTypeDef;
  22817. auto methodDef = methodInstance->mMethodDef;
  22818. auto methodDeclaration = methodDef->GetMethodDeclaration();
  22819. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22820. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  22821. if (methodInstance->mIsInnerOverride)
  22822. return false;
  22823. BfAstNode* declaringNode = methodDeclaration;
  22824. if (propertyMethodDeclaration != NULL)
  22825. declaringNode = propertyMethodDeclaration->mNameNode;
  22826. BfMethodInstance* methodOverriden = NULL;
  22827. bool usedMethod = false;
  22828. BfTokenNode* virtualToken = NULL;
  22829. if (propertyDeclaration != NULL)
  22830. virtualToken = propertyDeclaration->mVirtualSpecifier;
  22831. else if (methodDeclaration != NULL)
  22832. virtualToken = methodDeclaration->mVirtualSpecifier;
  22833. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  22834. {
  22835. //Fail: Static members cannot be marked as override, virtual, or abstract
  22836. }
  22837. else if (methodDef->mIsVirtual)
  22838. {
  22839. if (IsHotCompile())
  22840. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  22841. BfTypeInstance* checkBase = typeInstance;
  22842. // If we are in an extension, look in ourselves first
  22843. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  22844. checkBase = checkBase->mBaseType;
  22845. if (typeInstance->IsValueType())
  22846. {
  22847. if (typeInstance->mBaseType == NULL)
  22848. return false; // It's actually ValueType
  22849. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  22850. if (!methodDef->mIsOverride)
  22851. {
  22852. Fail("Structs cannot have virtual methods", virtualToken, true);
  22853. return false;
  22854. }
  22855. checkBase = mContext->mBfObjectType;
  22856. if (checkBase->mVirtualMethodTableSize == 0)
  22857. PopulateType(checkBase, BfPopulateType_Full);
  22858. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  22859. return false; // System circular ref, don't do struct checking on those
  22860. }
  22861. int virtualMethodMatchIdx = -1;
  22862. bool hadHidingError = false;
  22863. BfMethodInstance* bestOverrideMethodInstance = NULL;
  22864. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  22865. int bestOverrideMethodIdx = -1;
  22866. int ambiguousOverrideMethodIdx = -1;
  22867. if (checkBase != NULL)
  22868. {
  22869. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22870. auto lookupType = checkBase;
  22871. while (lookupType != NULL)
  22872. {
  22873. lookupType->mTypeDef->PopulateMemberSets();
  22874. BfMethodDef* nextMethodDef = NULL;
  22875. BfMemberSetEntry* entry;
  22876. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  22877. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  22878. while (nextMethodDef != NULL)
  22879. {
  22880. auto checkMethodDef = nextMethodDef;
  22881. nextMethodDef = nextMethodDef->mNextWithSameName;
  22882. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  22883. continue;
  22884. BfMethodInstance* baseMethodInstance = NULL;
  22885. int checkMethodIdx = -1;
  22886. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  22887. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  22888. {
  22889. if (lookupType->IsUnspecializedTypeVariation())
  22890. {
  22891. if (!lookupMethodInstance->mMethodDef->mIsOverride)
  22892. {
  22893. baseMethodInstance = lookupMethodInstance;
  22894. checkMethodIdx = -2;
  22895. }
  22896. }
  22897. if (baseMethodInstance == NULL)
  22898. continue;
  22899. }
  22900. if (baseMethodInstance == NULL)
  22901. {
  22902. checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  22903. if (checkMethodIdx >= baseVirtualMethodTable.mSize)
  22904. {
  22905. Fail("SlotVirtualMethod out of bounds", checkMethodDef->GetRefNode());
  22906. continue;
  22907. }
  22908. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22909. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22910. {
  22911. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22912. continue;
  22913. }
  22914. baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22915. if (baseMethodInstance == NULL)
  22916. {
  22917. AssertErrorState();
  22918. continue;
  22919. }
  22920. }
  22921. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22922. {
  22923. if (methodDef->mIsOverride)
  22924. {
  22925. BfMethodInstance* checkMethodInstance;
  22926. if (checkMethodIdx == -2)
  22927. checkMethodInstance = baseMethodInstance;
  22928. else if (typeInstance->IsValueType())
  22929. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22930. else
  22931. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22932. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22933. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22934. continue;
  22935. if (bestOverrideMethodInstance != NULL)
  22936. {
  22937. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22938. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22939. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22940. if (isBetter == isWorse)
  22941. {
  22942. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22943. }
  22944. else
  22945. {
  22946. if (isWorse)
  22947. continue;
  22948. ambiguousOverrideMethodInstance = NULL;
  22949. }
  22950. }
  22951. bestOverrideMethodInstance = checkMethodInstance;
  22952. bestOverrideMethodIdx = checkMethodIdx;
  22953. }
  22954. else
  22955. {
  22956. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22957. {
  22958. if (!hadHidingError)
  22959. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22960. hadHidingError = true;
  22961. }
  22962. }
  22963. }
  22964. }
  22965. lookupType = lookupType->mBaseType;
  22966. }
  22967. }
  22968. //TODO:
  22969. if ((checkBase != NULL)
  22970. && (false)
  22971. )
  22972. {
  22973. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22974. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  22975. {
  22976. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22977. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22978. {
  22979. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22980. continue;
  22981. }
  22982. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22983. if (baseMethodInstance == NULL)
  22984. {
  22985. AssertErrorState();
  22986. continue;
  22987. }
  22988. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22989. {
  22990. if (methodDef->mIsOverride)
  22991. {
  22992. BfMethodInstance* checkMethodInstance;
  22993. if (typeInstance->IsValueType())
  22994. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22995. else
  22996. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22997. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22998. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22999. continue;
  23000. if (bestOverrideMethodInstance != NULL)
  23001. {
  23002. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  23003. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  23004. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  23005. if (isBetter == isWorse)
  23006. {
  23007. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  23008. }
  23009. else
  23010. {
  23011. if (isWorse)
  23012. continue;
  23013. ambiguousOverrideMethodInstance = NULL;
  23014. }
  23015. }
  23016. bestOverrideMethodInstance = checkMethodInstance;
  23017. bestOverrideMethodIdx = checkMethodIdx;
  23018. }
  23019. else
  23020. {
  23021. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  23022. {
  23023. if (!hadHidingError)
  23024. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  23025. hadHidingError = true;
  23026. }
  23027. }
  23028. }
  23029. }
  23030. }
  23031. if (bestOverrideMethodInstance != NULL)
  23032. {
  23033. if (ambiguousOverrideMethodInstance != NULL)
  23034. {
  23035. bool allow = false;
  23036. // 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.
  23037. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  23038. bool canSeeEachOther = false;
  23039. //
  23040. {
  23041. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  23042. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  23043. canSeeEachOther = true;
  23044. }
  23045. //
  23046. {
  23047. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  23048. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  23049. canSeeEachOther = true;
  23050. }
  23051. if (!canSeeEachOther)
  23052. {
  23053. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  23054. }
  23055. else
  23056. {
  23057. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  23058. if (error != NULL)
  23059. {
  23060. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  23061. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  23062. }
  23063. }
  23064. }
  23065. }
  23066. if (bestOverrideMethodIdx == -2)
  23067. {
  23068. // Comes from an unspecialized variation
  23069. virtualMethodMatchIdx = bestOverrideMethodIdx;
  23070. }
  23071. else if ((bestOverrideMethodInstance != NULL) && (bestOverrideMethodIdx != -1))
  23072. {
  23073. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  23074. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  23075. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  23076. {
  23077. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  23078. {
  23079. BfTypeReference* returnTypeRef;
  23080. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  23081. {
  23082. returnTypeRef = propertyDeclaration->mTypeRef;
  23083. Fail("Property differs from overridden property by type", returnTypeRef, true);
  23084. }
  23085. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  23086. {
  23087. returnTypeRef = methodDeclaration->mReturnType;
  23088. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  23089. }
  23090. else
  23091. {
  23092. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  23093. }
  23094. return usedMethod;
  23095. }
  23096. }
  23097. if (methodDef->mIsOverride)
  23098. {
  23099. // We can have multiple matches when a virtual method is used to implement interface methods
  23100. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  23101. // vtable entries for this method signature
  23102. virtualMethodMatchIdx = bestOverrideMethodIdx;
  23103. if (!typeInstance->IsValueType())
  23104. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  23105. if (typeInstance->IsValueType())
  23106. {
  23107. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  23108. }
  23109. else
  23110. {
  23111. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  23112. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  23113. BfMethodInstance* setMethodInstance = methodInstance;
  23114. bool doOverride = false;
  23115. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  23116. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  23117. {
  23118. methodOverriden = overridenRef;
  23119. doOverride = true;
  23120. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  23121. {
  23122. bool isBetter = false;
  23123. bool isWorse = false;
  23124. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  23125. if (isBetter == isWorse)
  23126. {
  23127. // We have to resolve later per-project
  23128. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  23129. {
  23130. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  23131. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  23132. }
  23133. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  23134. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  23135. doOverride = false;
  23136. }
  23137. else
  23138. {
  23139. if ((isBetter) && (ambiguityContext != NULL))
  23140. {
  23141. ambiguityContext->Remove(virtualMethodMatchIdx);
  23142. }
  23143. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  23144. {
  23145. if (preferRootDefinition)
  23146. {
  23147. // Leave the master GCMarkMember
  23148. isBetter = false;
  23149. isWorse = true;
  23150. }
  23151. }
  23152. doOverride = isBetter;
  23153. }
  23154. }
  23155. }
  23156. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  23157. {
  23158. methodOverriden = overridenRef;
  23159. doOverride = true;
  23160. }
  23161. if (doOverride)
  23162. {
  23163. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  23164. _AddVirtualDecl(declMethodInstance);
  23165. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  23166. auto& implMethodRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  23167. if ((!mCompiler->mIsResolveOnly) && (implMethodRef.mMethodNum >= 0) &&
  23168. (implMethodRef.mTypeInstance == typeInstance) && (methodInstance->GetOwner() == typeInstance))
  23169. {
  23170. auto prevImplMethodInstance = (BfMethodInstance*)implMethodRef;
  23171. if (prevImplMethodInstance->mMethodDef->mDeclaringType->mProject != methodInstance->mMethodDef->mDeclaringType->mProject)
  23172. {
  23173. // We may need to have to previous method reified when we must re-slot in another project during vdata creation
  23174. BfReifyMethodDependency dep;
  23175. dep.mDepMethod = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  23176. dep.mMethodIdx = implMethodRef.mMethodNum;
  23177. typeInstance->mReifyMethodDependencies.Add(dep);
  23178. }
  23179. if (!methodInstance->mMangleWithIdx)
  23180. {
  23181. // Keep mangled names from conflicting
  23182. methodInstance->mMangleWithIdx = true;
  23183. if ((methodInstance->mIRFunction) && (methodInstance->mDeclModule->mIsModuleMutable))
  23184. {
  23185. StringT<4096> mangledName;
  23186. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  23187. methodInstance->mDeclModule->mBfIRBuilder->SetFunctionName(methodInstance->mIRFunction, mangledName);
  23188. }
  23189. }
  23190. }
  23191. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  23192. }
  23193. }
  23194. if (methodOverriden != NULL)
  23195. {
  23196. CheckOverridenMethod(methodInstance, methodOverriden);
  23197. }
  23198. }
  23199. }
  23200. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  23201. {
  23202. if (methodDef->mIsOverride)
  23203. {
  23204. BfTokenNode* overrideToken = NULL;
  23205. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  23206. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  23207. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  23208. overrideToken = methodDeclaration->mVirtualSpecifier;
  23209. if (overrideToken != NULL)
  23210. {
  23211. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  23212. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  23213. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  23214. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  23215. else
  23216. Fail("No suitable method found to override", overrideToken, true);
  23217. }
  23218. return usedMethod;
  23219. }
  23220. UniqueSlotVirtualMethod(methodInstance);
  23221. }
  23222. else
  23223. usedMethod = true;
  23224. if (typeInstance->IsValueType())
  23225. return usedMethod;
  23226. }
  23227. bool foundInterface = false;
  23228. bool hadAnyMatch = false;
  23229. // See if this method matches interfaces
  23230. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  23231. {
  23232. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  23233. if (ifaceInst->IsIncomplete())
  23234. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  23235. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  23236. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  23237. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  23238. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  23239. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  23240. continue;
  23241. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  23242. continue;
  23243. bool hadMatch = false;
  23244. BfMethodInstance* hadNameMatch = NULL;
  23245. BfType* expectedReturnType = NULL;
  23246. bool showedError = false;
  23247. // We go through our VTable looking for NULL entries within the interface sections
  23248. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  23249. // because a normal method declared in this type could have matched earlier
  23250. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  23251. ifaceInst->mTypeDef->PopulateMemberSets();
  23252. BfMethodDef* checkMethodDef = NULL;
  23253. BfMemberSetEntry* entry;
  23254. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  23255. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  23256. while (checkMethodDef != NULL)
  23257. {
  23258. int iMethodIdx = checkMethodDef->mIdx;
  23259. int iTableIdx = iMethodIdx + startIdx;
  23260. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  23261. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  23262. bool storeIFaceMethod = false;
  23263. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  23264. {
  23265. checkMethodDef = checkMethodDef->mNextWithSameName;
  23266. continue;
  23267. }
  23268. if (iMethodIdx >= ifaceInst->mMethodInstanceGroups.mSize)
  23269. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  23270. if (iMethodIdx >= ifaceInst->mMethodInstanceGroups.mSize)
  23271. {
  23272. InternalError("Interface slotting error", methodInstance->mMethodDef->GetMutNode());
  23273. break;
  23274. }
  23275. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  23276. auto iMethodInst = iMethodGroup.mDefault;
  23277. if (iMethodInst == NULL)
  23278. {
  23279. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  23280. AssertErrorState();
  23281. checkMethodDef = checkMethodDef->mNextWithSameName;
  23282. continue;
  23283. }
  23284. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  23285. hadNameMatch = iMethodInst;
  23286. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  23287. if ((!doesMethodSignatureMatch) && (interfaceMethodEntry->mMethodRef.IsNull()))
  23288. {
  23289. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  23290. }
  23291. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  23292. {
  23293. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  23294. {
  23295. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  23296. {
  23297. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  23298. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  23299. if (error != NULL)
  23300. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  23301. showedError = true;
  23302. }
  23303. }
  23304. }
  23305. if (doesMethodSignatureMatch)
  23306. {
  23307. usedMethod = true;
  23308. hadMatch = true;
  23309. hadAnyMatch = true;
  23310. storeIFaceMethod = true;
  23311. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  23312. {
  23313. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  23314. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance) && (!mIsComptimeModule))
  23315. {
  23316. // When autocompletion regenerates a single method body but not the whole type then
  23317. // we will see ourselves in the vtable already
  23318. return usedMethod;
  23319. }
  23320. bool isBetter = false;
  23321. bool isWorse = false;
  23322. isBetter = methodInstance->mReturnType == iMethodInst->mReturnType;
  23323. isWorse = prevMethod->mReturnType == iMethodInst->mReturnType;
  23324. if (isBetter == isWorse)
  23325. {
  23326. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  23327. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  23328. if ((isBetter) && (isWorse))
  23329. {
  23330. isBetter = methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst;
  23331. isWorse = prevMethod->mMethodInfoEx->mExplicitInterface == ifaceInst;
  23332. }
  23333. }
  23334. if (isBetter == isWorse)
  23335. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  23336. if (isBetter == isWorse)
  23337. {
  23338. if (ambiguityContext != NULL)
  23339. {
  23340. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  23341. }
  23342. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  23343. storeIFaceMethod = true;
  23344. }
  23345. else
  23346. {
  23347. if ((isBetter) && (ambiguityContext != NULL))
  23348. ambiguityContext->Remove(~iTableIdx);
  23349. storeIFaceMethod = isBetter;
  23350. }
  23351. }
  23352. }
  23353. if (storeIFaceMethod)
  23354. {
  23355. if (methodInstance->GetNumGenericParams() != 0)
  23356. _AddVirtualDecl(iMethodInst);
  23357. *iMethodPtr = methodInstance;
  23358. }
  23359. checkMethodDef = checkMethodDef->mNextWithSameName;
  23360. }
  23361. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  23362. {
  23363. if (expectedReturnType != NULL)
  23364. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  23365. else if (hadNameMatch != NULL)
  23366. {
  23367. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  23368. if (error != NULL)
  23369. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  23370. }
  23371. else
  23372. {
  23373. auto propertyDecl = methodDef->GetPropertyDeclaration();
  23374. if (propertyDecl != NULL)
  23375. {
  23376. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  23377. String name;
  23378. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  23379. name = "this[]";
  23380. else if (propertyDecl->mNameNode != NULL)
  23381. propertyDecl->mNameNode->ToString(name);
  23382. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  23383. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  23384. }
  23385. else
  23386. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  23387. }
  23388. }
  23389. }
  23390. // Any overriden virtual methods that were used in interfaces also need to be replaced
  23391. if (methodOverriden != NULL)
  23392. {
  23393. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  23394. {
  23395. if (methodEntry.mMethodRef == methodOverriden)
  23396. methodEntry.mMethodRef = methodInstance;
  23397. }
  23398. }
  23399. return usedMethod;
  23400. }
  23401. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  23402. {
  23403. auto methodDef = methodInstance->mMethodDef;
  23404. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  23405. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  23406. {
  23407. const char* protectionNames[] = { "disabled", "hidden", "private", "internal", "protected", "protected internal", "public" };
  23408. BF_STATIC_ASSERT(BF_ARRAY_COUNT(protectionNames) == BfProtection_COUNT);
  23409. BfAstNode* protectionRefNode = NULL;
  23410. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  23411. {
  23412. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  23413. if (protectionRefNode == NULL)
  23414. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  23415. if (protectionRefNode == NULL)
  23416. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  23417. }
  23418. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  23419. {
  23420. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  23421. if (protectionRefNode == NULL)
  23422. protectionRefNode = methodDeclaration->mNameNode;
  23423. }
  23424. if (protectionRefNode != NULL)
  23425. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  23426. }
  23427. }
  23428. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  23429. {
  23430. auto typeInstance = mCurTypeInstance;
  23431. auto methodDef = methodInstance->mMethodDef;
  23432. if (methodDef->mMethodType == BfMethodType_Ctor)
  23433. return true;
  23434. bool foundOverride = false;
  23435. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  23436. {
  23437. auto methodDeclaration = methodDef->GetMethodDeclaration();
  23438. BfAstNode* refNode = NULL;
  23439. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  23440. refNode = propertyDeclaration->mProtectionSpecifier;
  23441. else if (methodDeclaration != NULL)
  23442. refNode = methodDeclaration->mProtectionSpecifier;
  23443. Fail("Private interface methods must provide a body", refNode);
  23444. }
  23445. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  23446. {
  23447. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  23448. }
  23449. BfAstNode* declaringNode = methodDef->GetRefNode();
  23450. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  23451. {
  23452. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  23453. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  23454. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  23455. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  23456. continue;
  23457. ifaceInst->mTypeDef->PopulateMemberSets();
  23458. BfMethodDef* nextMethod = NULL;
  23459. BfMemberSetEntry* entry = NULL;
  23460. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  23461. nextMethod = (BfMethodDef*)entry->mMemberDef;
  23462. while (nextMethod != NULL)
  23463. {
  23464. auto checkMethod = nextMethod;
  23465. nextMethod = nextMethod->mNextWithSameName;
  23466. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  23467. if (ifaceMethod == NULL)
  23468. continue;
  23469. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  23470. {
  23471. if (methodDef->mIsOverride)
  23472. {
  23473. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  23474. {
  23475. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  23476. if (error != NULL)
  23477. {
  23478. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  23479. }
  23480. }
  23481. foundOverride = true;
  23482. }
  23483. else if (!methodDef->mIsNew)
  23484. {
  23485. auto error = Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  23486. if (error != NULL)
  23487. {
  23488. mCompiler->mPassInstance->MoreInfo("See inherited method", ifaceMethod->mMethodDef->GetRefNode());
  23489. }
  23490. }
  23491. }
  23492. }
  23493. }
  23494. if ((methodDef->mIsOverride) && (!foundOverride))
  23495. {
  23496. // This allows us to declare a method in the base definition or in an extension and then provide
  23497. // an implementation in a more-specific extension
  23498. typeInstance->mTypeDef->PopulateMemberSets();
  23499. BfMethodDef* nextMethod = NULL;
  23500. BfMemberSetEntry* entry = NULL;
  23501. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  23502. nextMethod = (BfMethodDef*)entry->mMemberDef;
  23503. while (nextMethod != NULL)
  23504. {
  23505. auto checkMethod = nextMethod;
  23506. nextMethod = nextMethod->mNextWithSameName;
  23507. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  23508. if (ifaceMethod == NULL)
  23509. continue;
  23510. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  23511. continue;
  23512. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  23513. {
  23514. foundOverride = true;
  23515. }
  23516. }
  23517. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  23518. // {
  23519. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  23520. // if (ifaceMethod == NULL)
  23521. // continue;
  23522. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  23523. // continue;
  23524. //
  23525. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  23526. // {
  23527. // foundOverride = true;
  23528. // }
  23529. // }
  23530. }
  23531. if (methodDef->mIsOverride)
  23532. {
  23533. if (!foundOverride)
  23534. {
  23535. BfTokenNode* overrideToken = NULL;
  23536. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  23537. overrideToken = propertyDeclaration->mVirtualSpecifier;
  23538. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  23539. overrideToken = methodDeclaration->mVirtualSpecifier;
  23540. if (overrideToken != NULL)
  23541. {
  23542. Fail("No suitable method found to override", overrideToken, true);
  23543. }
  23544. else
  23545. {
  23546. // Possible cause - DTOR with params
  23547. AssertErrorState();
  23548. }
  23549. }
  23550. return true;
  23551. }
  23552. // Generic methods can't be called virtually
  23553. if (methodInstance->GetNumGenericParams() != 0)
  23554. return true;
  23555. // Only public methods can be called virtually
  23556. if (methodDef->mProtection != BfProtection_Public)
  23557. return true;
  23558. UniqueSlotVirtualMethod(methodInstance);
  23559. return true;
  23560. }
  23561. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  23562. {
  23563. if (methodInstance->mMethodInfoEx == NULL)
  23564. return;
  23565. int wantMinDepth = -1;
  23566. if (mCurTypeInstance != NULL)
  23567. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  23568. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  23569. {
  23570. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  23571. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  23572. wantMinDepth = wantTypeMinDepth;
  23573. }
  23574. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  23575. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  23576. }
  23577. void BfModule::DbgFinish()
  23578. {
  23579. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  23580. return;
  23581. if (mAwaitingInitFinish)
  23582. FinishInit();
  23583. if (mHasForceLinkMarker)
  23584. return;
  23585. String markerName;
  23586. BfIRValue linkMarker;
  23587. if (mBfIRBuilder->DbgHasInfo())
  23588. {
  23589. bool needForceLinking = false;
  23590. if (WantsDebugHelpers())
  23591. {
  23592. for (auto& ownedType : mOwnedTypeInstances)
  23593. {
  23594. bool hasConfirmedReference = false;
  23595. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  23596. {
  23597. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  23598. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  23599. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)) &&
  23600. (methodInstGroup.mHasEmittedReference))
  23601. {
  23602. hasConfirmedReference = true;
  23603. }
  23604. }
  23605. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  23606. needForceLinking = true;
  23607. }
  23608. }
  23609. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  23610. {
  23611. BfMethodState methodState;
  23612. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  23613. methodState.mTempKind = BfMethodState::TempKind_Static;
  23614. mHasForceLinkMarker = true;
  23615. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  23616. SizedArray<BfIRType, 0> paramTypes;
  23617. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  23618. String linkName = "FORCELINKMOD_" + mModuleName;
  23619. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  23620. mBfIRBuilder->SetActiveFunction(func);
  23621. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  23622. mBfIRBuilder->SetInsertPoint(entryBlock);
  23623. auto firstType = mOwnedTypeInstances[0];
  23624. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  23625. SizedArray<BfIRMDNode, 1> diParamTypes;
  23626. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  23627. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  23628. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  23629. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  23630. methodState.mCurScope->mDIScope = diScope;
  23631. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  23632. SizedArray<BfIRValue, 8> args;
  23633. BfExprEvaluator exprEvaluator(this);
  23634. for (auto& ownedType : mOwnedTypeInstances)
  23635. {
  23636. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  23637. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  23638. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  23639. }
  23640. mBfIRBuilder->CreateRetVoid();
  23641. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  23642. }
  23643. }
  23644. }
  23645. bool BfModule::Finish()
  23646. {
  23647. BP_ZONE("BfModule::Finish");
  23648. BfLogSysM("BfModule finish: %p\n", this);
  23649. if (mHadBuildError)
  23650. {
  23651. // Don't AssertErrorState here, this current pass may not have failed but
  23652. // the module was still queued in mFinishedModuleWorkList
  23653. ClearModule();
  23654. return true;
  23655. }
  23656. if (mUsedSlotCount != -1)
  23657. {
  23658. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  23659. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  23660. }
  23661. if ((!mGeneratesCode) && (!mAddedToCount))
  23662. return true;
  23663. BF_ASSERT(mAddedToCount);
  23664. mAddedToCount = false;
  23665. mAwaitingFinish = false;
  23666. mCompiler->mStats.mModulesFinished++;
  23667. if (HasCompiledOutput())
  23668. {
  23669. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  23670. DbgFinish();
  23671. if (mAwaitingInitFinish)
  23672. FinishInit();
  23673. for (auto ownedTypeInst : mOwnedTypeInstances)
  23674. {
  23675. // Generate dbg info and add global variables if we haven't already
  23676. mBfIRBuilder->PopulateType(ownedTypeInst);
  23677. }
  23678. if (mBfIRBuilder->DbgHasInfo())
  23679. {
  23680. mBfIRBuilder->DbgFinalize();
  23681. }
  23682. String objOutputPath;
  23683. String irOutputPath;
  23684. mIsModuleMutable = false;
  23685. //mOutFileNames.Clear();
  23686. BF_ASSERT(((int)mOutFileNames.size() >= mExtensionCount) || (mParentModule != NULL));
  23687. bool writeModule = mBfIRBuilder->HasExports();
  23688. String outputPath;
  23689. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  23690. auto& compilerOpts = mCompiler->mOptions;
  23691. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  23692. auto moduleOptions = GetModuleOptions();
  23693. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  23694. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  23695. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  23696. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  23697. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  23698. codeGenOptions.mVirtualMethodOfs = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  23699. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  23700. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  23701. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  23702. bool allowWriteToLib = true;
  23703. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  23704. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  23705. {
  23706. codeGenOptions.mWriteToLib = true;
  23707. mWroteToLib = true;
  23708. }
  23709. else
  23710. {
  23711. mWroteToLib = false;
  23712. }
  23713. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  23714. {
  23715. outputPath = mModuleName;
  23716. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  23717. BfModuleFileName moduleFileName;
  23718. if (mParentModule != NULL)
  23719. {
  23720. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  23721. {
  23722. if (checkPair.mValue == this)
  23723. moduleFileName.mProjects = checkPair.mKey;
  23724. }
  23725. }
  23726. moduleFileName.mProjects.Add(mProject);
  23727. if (fileIdx > 0)
  23728. outputPath += StrFormat("@%d", fileIdx + 1);
  23729. if (mCompiler->mOptions.mWriteIR)
  23730. irOutputPath = outputPath + ".ll";
  23731. if (mCompiler->mOptions.mGenerateObj)
  23732. {
  23733. objOutputPath = outputPath + BF_OBJ_EXT;
  23734. moduleFileName.mFileName = objOutputPath;
  23735. }
  23736. else if (mCompiler->mOptions.mWriteIR)
  23737. {
  23738. moduleFileName.mFileName = irOutputPath;
  23739. }
  23740. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  23741. {
  23742. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  23743. }
  23744. moduleFileName.mModuleWritten = writeModule;
  23745. moduleFileName.mWroteToLib = mWroteToLib;
  23746. if (!mOutFileNames.Contains(moduleFileName))
  23747. mOutFileNames.Add(moduleFileName);
  23748. }
  23749. if (mCompiler->IsHotCompile())
  23750. {
  23751. codeGenOptions.mIsHotCompile = true;
  23752. if (mParentModule != NULL)
  23753. mParentModule->mHadHotObjectWrites = true;
  23754. mHadHotObjectWrites = true;
  23755. }
  23756. //TODO: Testing VDATA
  23757. /*if (mModuleName == "vdata")
  23758. {
  23759. codeGenOptions.mOptLevel = 4;
  23760. }*/
  23761. codeGenOptions.GenerateHash();
  23762. BP_ZONE("BfModule::Finish.WriteObjectFile");
  23763. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  23764. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  23765. mLastModuleWrittenRevision = mCompiler->mRevision;
  23766. }
  23767. else
  23768. {
  23769. for (auto type : mOwnedTypeInstances)
  23770. {
  23771. BF_ASSERT((!type->IsIncomplete()) || (type->IsSpecializedByAutoCompleteMethod()));
  23772. }
  23773. }
  23774. for (auto& specModulePair : mSpecializedMethodModules)
  23775. {
  23776. auto specModule = specModulePair.mValue;
  23777. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  23778. {
  23779. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  23780. }
  23781. }
  23782. CleanupFileInstances();
  23783. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  23784. return true;
  23785. }
  23786. void BfModule::ReportMemory(MemReporter* memReporter)
  23787. {
  23788. memReporter->Add(sizeof(BfModule));
  23789. if (mBfIRBuilder != NULL)
  23790. {
  23791. memReporter->BeginSection("IRBuilder_ConstData");
  23792. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  23793. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  23794. memReporter->EndSection();
  23795. memReporter->BeginSection("IRBuilder_BFIR");
  23796. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  23797. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  23798. memReporter->EndSection();
  23799. memReporter->Add(sizeof(BfIRBuilder));
  23800. }
  23801. memReporter->BeginSection("FileInstanceMap");
  23802. memReporter->AddMap(mFileInstanceMap);
  23803. memReporter->AddMap(mNamedFileInstanceMap);
  23804. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  23805. memReporter->EndSection();
  23806. memReporter->AddVec(mOwnedTypeInstances, false);
  23807. memReporter->AddVec(mSpecializedMethodModules, false);
  23808. memReporter->AddVec(mOutFileNames, false);
  23809. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  23810. memReporter->AddMap(mInterfaceSlotRefs, false);
  23811. memReporter->AddMap(mStaticFieldRefs, false);
  23812. memReporter->AddMap(mClassVDataRefs, false);
  23813. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  23814. memReporter->AddMap(mTypeDataRefs, false);
  23815. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  23816. memReporter->AddMap(mDeferredMethodCallData, false);
  23817. memReporter->AddHashSet(mDeferredMethodIds, false);
  23818. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  23819. }
  23820. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  23821. // be transient through the next compile
  23822. void BfModule::ClearModuleData(bool clearTransientData)
  23823. {
  23824. BfLogSysM("ClearModuleData %p\n", this);
  23825. if (mAddedToCount)
  23826. {
  23827. mCompiler->mStats.mModulesFinished++;
  23828. mAddedToCount = false;
  23829. }
  23830. mDICompileUnit = BfIRMDNode();
  23831. if (clearTransientData)
  23832. mIncompleteMethodCount = 0;
  23833. mHasGenericMethods = false;
  23834. // We don't want to clear these because we want it to persist through module extensions-
  23835. // otherwise we may think an extension succeeds even though the base module failed
  23836. //mHadBuildError = false;
  23837. //mHadBuildWarning = false;
  23838. mClassVDataRefs.Clear();
  23839. mClassVDataExtRefs.Clear();
  23840. for (auto& kv : mTypeDataRefs)
  23841. kv.mValue = BfIRValue();
  23842. mStringCharPtrPool.Clear();
  23843. mStringObjectPool.Clear();
  23844. mStaticFieldRefs.Clear();
  23845. BF_ASSERT(!mIgnoreErrors);
  23846. for (auto prevIRBuilder : mPrevIRBuilders)
  23847. delete prevIRBuilder;
  23848. mPrevIRBuilders.Clear();
  23849. for (auto& specPair : mSpecializedMethodModules)
  23850. {
  23851. auto specModule = specPair.mValue;
  23852. specModule->ClearModuleData();
  23853. }
  23854. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  23855. mBuiltInFuncs[i] = BfIRFunction();
  23856. if (mNextAltModule != NULL)
  23857. mNextAltModule->ClearModuleData();
  23858. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  23859. mIsModuleMutable = false;
  23860. delete mBfIRBuilder;
  23861. mBfIRBuilder = NULL;
  23862. mWantsIRIgnoreWrites = false;
  23863. }
  23864. void BfModule::DisownMethods()
  23865. {
  23866. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  23867. mBuiltInFuncs[i] = BfIRFunction();
  23868. BfModule* methodModule = this;
  23869. if (mParentModule != NULL)
  23870. methodModule = mParentModule;
  23871. for (auto typeInst : methodModule->mOwnedTypeInstances)
  23872. {
  23873. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  23874. {
  23875. if (methodGroup.mDefault != NULL)
  23876. {
  23877. if (methodGroup.mDefault->mIRFunction)
  23878. {
  23879. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  23880. if (methodGroup.mDefault->mDeclModule == this)
  23881. {
  23882. methodGroup.mDefault->mIRFunction = BfIRFunction();
  23883. }
  23884. }
  23885. }
  23886. if (methodGroup.mMethodSpecializationMap != NULL)
  23887. {
  23888. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  23889. {
  23890. auto methodInstance = mapPair.mValue;
  23891. if (methodInstance->mDeclModule == this)
  23892. {
  23893. methodInstance->mIRFunction = BfIRFunction();
  23894. }
  23895. }
  23896. }
  23897. }
  23898. }
  23899. }
  23900. void BfModule::ClearModule()
  23901. {
  23902. ClearModuleData();
  23903. DisownMethods();
  23904. for (auto& specPair : mSpecializedMethodModules)
  23905. {
  23906. auto specModule = specPair.mValue;
  23907. specModule->ClearModule();
  23908. }
  23909. if (mNextAltModule != NULL)
  23910. mNextAltModule->ClearModule();
  23911. }