BfModule.cpp 906 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683
  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. int mCurAppendAlign;
  419. public:
  420. AppendAllocVisitor()
  421. {
  422. mFailed = false;
  423. mIsFirstConstPass = false;
  424. mCurAppendAlign = 1;
  425. }
  426. void EmitAppendAlign(int align, int sizeMultiple = 0)
  427. {
  428. if (align <= 1)
  429. return;
  430. if (mIsFirstConstPass)
  431. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  432. if (sizeMultiple == 0)
  433. sizeMultiple = align;
  434. if (mCurAppendAlign == 0)
  435. mCurAppendAlign = sizeMultiple;
  436. else
  437. {
  438. if (sizeMultiple % align == 0)
  439. mCurAppendAlign = align;
  440. else
  441. mCurAppendAlign = sizeMultiple % align;
  442. }
  443. BF_ASSERT(mCurAppendAlign > 0);
  444. if (mConstAccum)
  445. {
  446. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  447. if (constant != NULL)
  448. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  449. else
  450. BF_ASSERT(mIsFirstConstPass);
  451. return;
  452. }
  453. mModule->EmitAppendAlign(align, sizeMultiple);
  454. }
  455. void Visit(BfAstNode* astNode) override
  456. {
  457. mModule->VisitChild(astNode);
  458. }
  459. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  460. {
  461. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  462. {
  463. if (newToken->GetToken() == BfToken_Append)
  464. {
  465. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  466. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  467. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  468. BfArrayType* arrayType = NULL;
  469. bool isArrayAlloc = false;
  470. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  471. SizedArray<BfIRValue, 2> dimLengthVals;
  472. BfType* origResolvedTypeRef = NULL;
  473. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  474. {
  475. if (variableDecl != NULL)
  476. {
  477. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  478. if (origResolvedTypeRef->IsObject())
  479. {
  480. if (origResolvedTypeRef->IsArray())
  481. {
  482. arrayType = (BfArrayType*)origResolvedTypeRef;
  483. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  484. isArrayAlloc = true;
  485. }
  486. }
  487. else if (origResolvedTypeRef->IsPointer())
  488. {
  489. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  490. }
  491. }
  492. }
  493. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  494. {
  495. isArrayAlloc = true;
  496. bool handled = false;
  497. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  498. {
  499. if (variableDecl->mTypeRef != NULL)
  500. {
  501. auto variableType = mModule->ResolveTypeRef(variableDecl->mTypeRef);
  502. if (variableType != NULL)
  503. {
  504. if (variableType->IsArray())
  505. origResolvedTypeRef = variableType->GetUnderlyingType();
  506. }
  507. handled = true;
  508. }
  509. }
  510. if (!handled)
  511. {
  512. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType, BfPopulateType_Declaration);
  513. }
  514. if (origResolvedTypeRef == NULL)
  515. {
  516. mModule->AssertErrorState();
  517. return;
  518. }
  519. int dimensions = 1;
  520. if (arrayTypeRef->mParams.size() != 0)
  521. {
  522. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  523. for (auto arg : arrayTypeRef->mParams)
  524. {
  525. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  526. {
  527. if (tokenNode->GetToken() == BfToken_Comma)
  528. {
  529. if (isRawArrayAlloc)
  530. {
  531. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  532. continue;
  533. }
  534. dimensions++;
  535. continue;
  536. }
  537. }
  538. auto expr = BfNodeDynCast<BfExpression>(arg);
  539. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  540. {
  541. mModule->CreateValueFromExpression(expr, intType);
  542. continue;
  543. }
  544. BfTypedValue dimLength;
  545. if (expr == NULL)
  546. {
  547. // Not specified
  548. dimLengthVals.push_back(BfIRValue());
  549. continue;
  550. }
  551. if (arg != NULL)
  552. dimLength = mModule->CreateValueFromExpression(expr, intType);
  553. if (!dimLength)
  554. {
  555. dimLength = mModule->GetDefaultTypedValue(intType);
  556. }
  557. dimLengthVals.push_back(dimLength.mValue);
  558. }
  559. }
  560. if (!isRawArrayAlloc)
  561. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  562. }
  563. if (origResolvedTypeRef == NULL)
  564. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  565. if (origResolvedTypeRef == NULL)
  566. {
  567. mModule->AssertErrorState();
  568. return;
  569. }
  570. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  571. auto resolvedTypeRef = origResolvedTypeRef;
  572. auto resultType = resolvedTypeRef;
  573. BfIRValue sizeValue;
  574. int curAlign = 0;
  575. if (isArrayAlloc)
  576. {
  577. int dimensions = 1;
  578. if (arrayType != NULL)
  579. dimensions = arrayType->mDimensions;
  580. bool sizeFailed = false;
  581. //
  582. {
  583. BfAstNode* initNode = objCreateExpr;
  584. for (int dim = 0; dim < dimensions; dim++)
  585. {
  586. BfAstNode* nextInitNode = NULL;
  587. int dimSize = -1;
  588. if (initNode == objCreateExpr)
  589. {
  590. dimSize = objCreateExpr->mArguments.size();
  591. if (!objCreateExpr->mArguments.IsEmpty())
  592. nextInitNode = objCreateExpr->mArguments[0];
  593. }
  594. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  595. {
  596. dimSize = (int)tupleNode->mCommas.size() + 1;
  597. }
  598. if (dimSize >= 0)
  599. {
  600. if (dim >= dimLengthVals.size())
  601. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  602. }
  603. else
  604. {
  605. sizeFailed = true;
  606. }
  607. }
  608. }
  609. BfIRValue allocCount;
  610. if (!sizeFailed)
  611. {
  612. if (!dimLengthVals.IsEmpty())
  613. {
  614. allocCount = dimLengthVals[0];
  615. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  616. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  617. }
  618. }
  619. if (!allocCount)
  620. {
  621. mFailed = true;
  622. if (!mIsFirstConstPass)
  623. {
  624. if (!mConstAccum)
  625. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  626. return;
  627. }
  628. }
  629. mModule->PopulateType(resultType, resultType->IsValueType() ? BfPopulateType_Data : BfPopulateType_Declaration);
  630. if (isRawArrayAlloc)
  631. {
  632. curAlign = resultType->mAlign;
  633. EmitAppendAlign(resultType->mAlign);
  634. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  635. }
  636. else
  637. {
  638. if (arrayType == NULL)
  639. arrayType = mModule->CreateArrayType(resultType, 1);
  640. // Array is a special case where the total size isn't aligned with mAlign
  641. // since we add arbitrary elements to the end without padding the end to align
  642. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  643. curAlign = arrayType->mAlign;
  644. auto firstElementField = &arrayType->mFieldInstances.back();
  645. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  646. sizeValue = mModule->GetConstValue(arrayClassSize);
  647. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  648. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  649. }
  650. }
  651. else
  652. {
  653. auto typeInst = resultType->ToTypeInstance();
  654. if (typeInst != NULL)
  655. {
  656. curAlign = typeInst->mInstAlign;
  657. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  658. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  659. }
  660. else
  661. {
  662. curAlign = resultType->mAlign;
  663. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  664. sizeValue = mModule->GetConstValue(resultType->mSize);
  665. }
  666. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  667. BfExprEvaluator exprEvaluator(mModule);
  668. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  669. BfFunctionBindResult bindResult;
  670. bindResult.mWantsArgs = true;
  671. exprEvaluator.mFunctionBindResult = &bindResult;
  672. SizedArray<BfExpression*, 8> copiedArgs;
  673. for (BfExpression* arg : objCreateExpr->mArguments)
  674. copiedArgs.push_back(arg);
  675. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  676. BfResolvedArgs argValues(&sizedArgExprs);
  677. if (typeInst != NULL)
  678. {
  679. exprEvaluator.ResolveArgValues(argValues);
  680. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, BfMethodGenericArguments(), true);
  681. }
  682. exprEvaluator.mFunctionBindResult = NULL;
  683. if (bindResult.mMethodInstance != NULL)
  684. {
  685. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  686. {
  687. auto calcAppendArgs = bindResult.mIRArgs;
  688. BF_ASSERT(calcAppendArgs[0].IsFake());
  689. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  690. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  691. auto subDependSize = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, calcAppendArgs);
  692. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  693. {
  694. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  695. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  696. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  697. }
  698. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  699. if ((!subDependSize) && (!mConstAccum))
  700. {
  701. BF_ASSERT(calcAppendMethodModule.mFunc);
  702. subDependSize = exprEvaluator.CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  703. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  704. }
  705. if (subDependSize)
  706. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  707. else
  708. mFailed = true;
  709. }
  710. }
  711. }
  712. if (sizeValue)
  713. {
  714. if (mConstAccum)
  715. {
  716. if (!sizeValue.IsConst())
  717. {
  718. mFailed = true;
  719. if (!mIsFirstConstPass)
  720. return;
  721. }
  722. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  723. }
  724. else
  725. {
  726. auto prevVal = mModule->mBfIRBuilder->CreateAlignedLoad(accumValuePtr, intPtrType->mAlign);
  727. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  728. mModule->mBfIRBuilder->CreateAlignedStore(addedVal, accumValuePtr, intPtrType->mAlign);
  729. }
  730. }
  731. }
  732. }
  733. }
  734. void Visit(BfObjectCreateExpression* objCreateExpr) override
  735. {
  736. DoObjectCreate(objCreateExpr, NULL);
  737. }
  738. void Visit(BfVariableDeclaration* varDecl) override
  739. {
  740. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  741. {
  742. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  743. DoObjectCreate(objectCreateExpr, varDecl);
  744. else
  745. VisitChild(varDecl->mInitializer);
  746. if (varDecl->mNameNode != NULL)
  747. {
  748. BfLocalVariable* localDef = new BfLocalVariable();
  749. localDef->mName = varDecl->mNameNode->ToString();
  750. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  751. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  752. localDef->mIsReadOnly = true;
  753. localDef->mParamFailed = true;
  754. localDef->mReadFromId = 0;
  755. mModule->AddLocalVariableDef(localDef);
  756. }
  757. }
  758. else
  759. {
  760. mModule->Visit(varDecl);
  761. }
  762. }
  763. void Visit(BfExpressionStatement* exprStatement) override
  764. {
  765. VisitChild(exprStatement->mExpression);
  766. }
  767. // void Visit(BfIfStatement* ifStmt) override
  768. // {
  769. // mModule->DoIfStatement(ifStmt,
  770. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  771. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  772. // }
  773. void Visit(BfBlock* block) override
  774. {
  775. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  776. return;
  777. int appendAllocIdx = -1;
  778. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  779. {
  780. auto child = block->mChildArr.mVals[childIdx];
  781. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  782. {
  783. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  784. {
  785. auto emitChild = block->mChildArr.mVals[emitIdx];
  786. mModule->UpdateSrcPos(emitChild);
  787. VisitChild(emitChild);
  788. if ((mFailed) && (!mIsFirstConstPass))
  789. break;
  790. }
  791. break;
  792. }
  793. }
  794. }
  795. };
  796. //////////////////////////////////////////////////////////////////////////
  797. BfModule* gLastCreatedModule = NULL;
  798. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  799. {
  800. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  801. gLastCreatedModule = this;
  802. mContext = context;
  803. mModuleName = moduleName;
  804. if (!moduleName.empty())
  805. {
  806. StringT<256> upperModuleName = moduleName;
  807. MakeUpper(upperModuleName);
  808. mContext->mUsedModuleNames.Add(upperModuleName);
  809. }
  810. mAddedToCount = false;
  811. mParentModule = NULL;
  812. mNextAltModule = NULL;
  813. mBfIRBuilder = NULL;
  814. mWantsIRIgnoreWrites = false;
  815. mModuleOptions = NULL;
  816. mLastUsedRevision = -1;
  817. mUsedSlotCount = -1;
  818. mIsReified = true;
  819. mGeneratesCode = true;
  820. mReifyQueued = false;
  821. mIsSpecialModule = false;
  822. mIsComptimeModule = false;
  823. mIsScratchModule = false;
  824. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  825. mHadBuildError = false;
  826. mHadBuildWarning = false;
  827. mIgnoreErrors = false;
  828. mHadIgnoredError = false;
  829. mIgnoreWarnings = false;
  830. mReportErrors = true;
  831. mIsInsideAutoComplete = false;
  832. mIsDeleting = false;
  833. mSkipInnerLookup = false;
  834. mIsHotModule = false;
  835. mSetIllegalSrcPosition = false;
  836. mNoResolveGenericParams = false;
  837. mWroteToLib = false;
  838. mContext = context;
  839. mCompiler = context->mCompiler;
  840. mSystem = mCompiler->mSystem;
  841. mProject = NULL;
  842. mCurMethodState = NULL;
  843. mAttributeState = NULL;
  844. mCurLocalMethodId = 0;
  845. mParentNodeEntry = NULL;
  846. mRevision = -1;
  847. mRebuildIdx = 0;
  848. mLastModuleWrittenRevision = 0;
  849. mIsModuleMutable = false;
  850. mExtensionCount = 0;
  851. mIncompleteMethodCount = 0;
  852. mOnDemandMethodCount = 0;
  853. mHasGenericMethods = false;
  854. mCurMethodInstance = NULL;
  855. mCurTypeInstance = NULL;
  856. mAwaitingInitFinish = false;
  857. mAwaitingFinish = false;
  858. mHasFullDebugInfo = false;
  859. mHadHotObjectWrites = false;
  860. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  861. mBuiltInFuncs[i] = BfIRFunction();
  862. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  863. }
  864. void BfReportMemory();
  865. BfModule::~BfModule()
  866. {
  867. mRevision = -2;
  868. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  869. if (!mIsDeleting)
  870. RemoveModuleData();
  871. }
  872. void BfModule::RemoveModuleData()
  873. {
  874. BF_ASSERT(!mIsDeleting);
  875. if (!mModuleName.empty())
  876. {
  877. // Note: module names not necessarily unique
  878. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  879. }
  880. CleanupFileInstances();
  881. delete mBfIRBuilder;
  882. mBfIRBuilder = NULL;
  883. //delete mCpu;
  884. for (auto prevModule : mPrevIRBuilders)
  885. delete prevModule;
  886. mPrevIRBuilders.Clear();
  887. for (auto& pairVal : mDeferredMethodCallData)
  888. delete pairVal.mValue;
  889. mDeferredMethodCallData.Clear();
  890. mDeferredMethodIds.Clear();
  891. for (auto& specModulePair : mSpecializedMethodModules)
  892. delete specModulePair.mValue;
  893. mSpecializedMethodModules.Clear();
  894. if (mNextAltModule != NULL)
  895. delete mNextAltModule;
  896. mNextAltModule = NULL;
  897. if (mModuleOptions != NULL)
  898. delete mModuleOptions;
  899. mModuleOptions = NULL;
  900. BfReportMemory();
  901. }
  902. void BfModule::Init(bool isFullRebuild)
  903. {
  904. mContext->mFinishedModuleWorkList.Remove(this);
  905. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  906. BF_ASSERT(mIsReified);
  907. if (!mIsScratchModule)
  908. {
  909. mCompiler->mStats.mModulesStarted++;
  910. if (mIsReified)
  911. mCompiler->mStats.mReifiedModuleCount++;
  912. mAddedToCount = true;
  913. }
  914. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  915. mFuncReferences.Clear();
  916. mClassVDataRefs.Clear();
  917. mClassVDataExtRefs.Clear();
  918. //mTypeDataRefs.Clear();
  919. mDbgRawAllocDataRefs.Clear();
  920. CleanupFileInstances();
  921. mStaticFieldRefs.Clear();
  922. //mInterfaceSlotRefs.Clear();
  923. // If we are just doing an extension then the ownede types aren't rebuilt.
  924. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  925. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  926. if (isFullRebuild)
  927. mRevision = mCompiler->mRevision;
  928. BF_ASSERT(mCurTypeInstance == NULL);
  929. mIsModuleMutable = true;
  930. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  931. if (!mIsComptimeModule)
  932. {
  933. #ifdef _DEBUG
  934. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  935. #else
  936. EnsureIRBuilder(false);
  937. #endif
  938. }
  939. mCurMethodState = NULL;
  940. mAwaitingInitFinish = true;
  941. mOnDemandMethodCount = 0;
  942. mAwaitingFinish = false;
  943. mHasForceLinkMarker = false;
  944. mUsedSlotCount = -1;
  945. }
  946. bool BfModule::WantsFinishModule()
  947. {
  948. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  949. }
  950. bool BfModule::IsHotCompile()
  951. {
  952. return mCompiler->IsHotCompile() && !mIsComptimeModule;
  953. }
  954. void BfModule::FinishInit()
  955. {
  956. BF_ASSERT(mAwaitingInitFinish);
  957. auto moduleOptions = GetModuleOptions();
  958. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  959. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple, mCompiler->mOptions.mTargetCPU);
  960. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  961. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  962. {
  963. // Og+ requires debug info
  964. moduleOptions.mEmitDebugInfo = 1;
  965. }
  966. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  967. if (mIsComptimeModule)
  968. mHasFullDebugInfo = true;
  969. if (((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified)) ||
  970. (mIsComptimeModule))
  971. {
  972. mBfIRBuilder->DbgInit();
  973. }
  974. else
  975. mHasFullDebugInfo = false;
  976. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  977. ((moduleOptions.mEmitDebugInfo != 0)))
  978. {
  979. if (mCompiler->mOptions.IsCodeView())
  980. {
  981. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  982. }
  983. else
  984. {
  985. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  986. }
  987. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  988. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  989. }
  990. mAwaitingInitFinish = false;
  991. }
  992. void BfModule::CalcGeneratesCode()
  993. {
  994. if ((!mIsReified) || (mIsScratchModule))
  995. {
  996. mGeneratesCode = false;
  997. return;
  998. }
  999. mGeneratesCode = false;
  1000. for (auto typeInst : mOwnedTypeInstances)
  1001. if (!typeInst->IsInterface())
  1002. mGeneratesCode = true;
  1003. }
  1004. void BfModule::ReifyModule()
  1005. {
  1006. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  1007. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  1008. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  1009. mIsReified = true;
  1010. CalcGeneratesCode();
  1011. mReifyQueued = false;
  1012. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  1013. mCompiler->mStats.mModulesReified++;
  1014. }
  1015. void BfModule::UnreifyModule()
  1016. {
  1017. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  1018. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  1019. mIsReified = false;
  1020. CalcGeneratesCode();
  1021. mReifyQueued = false;
  1022. StartNewRevision(RebuildKind_None, true);
  1023. mCompiler->mStats.mModulesUnreified++;
  1024. }
  1025. void BfModule::CleanupFileInstances()
  1026. {
  1027. for (auto& itr : mNamedFileInstanceMap)
  1028. {
  1029. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  1030. delete itr.mValue;
  1031. }
  1032. mCurFilePosition.mFileInstance = NULL;//
  1033. mFileInstanceMap.Clear();
  1034. mNamedFileInstanceMap.Clear();
  1035. }
  1036. void BfModule::Cleanup()
  1037. {
  1038. CleanupFileInstances();
  1039. }
  1040. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  1041. {
  1042. if (HasCompiledOutput())
  1043. {
  1044. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  1045. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  1046. {
  1047. StartExtension();
  1048. }
  1049. }
  1050. else
  1051. {
  1052. EnsureIRBuilder();
  1053. }
  1054. }
  1055. void BfModule::SetupIRBuilder(bool dbgVerifyCodeGen)
  1056. {
  1057. if (mIsScratchModule)
  1058. {
  1059. mBfIRBuilder->mIgnoreWrites = true;
  1060. BF_ASSERT(!dbgVerifyCodeGen);
  1061. }
  1062. #ifdef _DEBUG
  1063. if (mCompiler->mIsResolveOnly)
  1064. {
  1065. // For "deep" verification testing
  1066. /*if (!mIsSpecialModule)
  1067. dbgVerifyCodeGen = true;*/
  1068. // We only want to turn this off on smaller builds for testing
  1069. mBfIRBuilder->mIgnoreWrites = true;
  1070. if (dbgVerifyCodeGen)
  1071. mBfIRBuilder->mIgnoreWrites = false;
  1072. if (!mBfIRBuilder->mIgnoreWrites)
  1073. {
  1074. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  1075. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1076. }
  1077. }
  1078. else if (!mGeneratesCode)
  1079. {
  1080. mBfIRBuilder->mIgnoreWrites = true;
  1081. }
  1082. else
  1083. {
  1084. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  1085. // code as we walk the AST
  1086. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1087. if (
  1088. (mModuleName == "-")
  1089. //|| (mModuleName == "")
  1090. //|| (mModuleName == "Tests_FuncRefs")
  1091. )
  1092. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1093. // Just for testing!
  1094. //mBfIRBuilder->mIgnoreWrites = true;
  1095. }
  1096. #else
  1097. if (mCompiler->mIsResolveOnly)
  1098. {
  1099. // Always ignore writes in resolveOnly for release builds
  1100. mBfIRBuilder->mIgnoreWrites = true;
  1101. }
  1102. else
  1103. {
  1104. // Just for memory testing! This breaks everything.
  1105. //mBfIRBuilder->mIgnoreWrites = true;
  1106. // For "deep" verification testing
  1107. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1108. }
  1109. #endif
  1110. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  1111. }
  1112. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  1113. {
  1114. BF_ASSERT(!mIsDeleting);
  1115. if (mBfIRBuilder == NULL)
  1116. {
  1117. if ((!mIsScratchModule) && (!mAddedToCount))
  1118. {
  1119. mCompiler->mStats.mModulesStarted++;
  1120. mAddedToCount = true;
  1121. }
  1122. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  1123. /*if (mCompiler->mIsResolveOnly)
  1124. BF_ASSERT(mIsResolveOnly);*/
  1125. mBfIRBuilder = new BfIRBuilder(this);
  1126. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  1127. SetupIRBuilder(dbgVerifyCodeGen);
  1128. }
  1129. }
  1130. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1131. {
  1132. String name = "FORCELINKMOD_" + module->mModuleName;
  1133. if (outName != NULL)
  1134. *outName = name;
  1135. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1136. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1137. }
  1138. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1139. {
  1140. BP_ZONE("BfModule::StartNewRevision");
  1141. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1142. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1143. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1144. if (mCompiler->mCompileState == BfCompiler::CompileState_Cleanup)
  1145. {
  1146. // Cleaning up local methods may cause some necessary NewRevisions
  1147. force = true;
  1148. }
  1149. // Already on new revision?
  1150. if ((mRevision == mCompiler->mRevision) && (!force))
  1151. return;
  1152. mHadBuildError = false;
  1153. mHadBuildWarning = false;
  1154. mExtensionCount = 0;
  1155. mRevision = mCompiler->mRevision;
  1156. mRebuildIdx++;
  1157. ClearModuleData(!force);
  1158. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1159. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1160. {
  1161. mStringPoolRefs.Clear();
  1162. mUnreifiedStringPoolRefs.Clear();
  1163. }
  1164. mDllImportEntries.Clear();
  1165. mImportFileNames.Clear();
  1166. for (auto& pairVal : mDeferredMethodCallData)
  1167. delete pairVal.mValue;
  1168. mDeferredMethodCallData.Clear();
  1169. mDeferredMethodIds.Clear();
  1170. mModuleRefs.Clear();
  1171. mOutFileNames.Clear();
  1172. mTypeDataRefs.Clear();
  1173. mInterfaceSlotRefs.Clear();
  1174. if (rebuildKind == BfModule::RebuildKind_None)
  1175. {
  1176. for (auto& specPair : mSpecializedMethodModules)
  1177. {
  1178. auto specModule = specPair.mValue;
  1179. if (specModule->mIsReified != mIsReified)
  1180. {
  1181. if (mIsReified)
  1182. specModule->ReifyModule();
  1183. else
  1184. specModule->UnreifyModule();
  1185. }
  1186. }
  1187. }
  1188. else
  1189. {
  1190. for (auto& specPair : mSpecializedMethodModules)
  1191. {
  1192. auto specModule = specPair.mValue;
  1193. BfLogSysM("Setting module mIsDeleting %p due to parent module starting a new revision\n", specModule);
  1194. // This module is no longer needed
  1195. specModule->RemoveModuleData();
  1196. specModule->mIsDeleting = true;
  1197. mContext->mDeletingModules.Add(specModule);
  1198. }
  1199. }
  1200. mSpecializedMethodModules.Clear();
  1201. delete mNextAltModule;
  1202. mNextAltModule = NULL;
  1203. BF_ASSERT(mModuleOptions == NULL);
  1204. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1205. bool needsTypePopulated = false;
  1206. int oldOnDemandCount = 0;
  1207. // We don't have to rebuild types in the unspecialized module because there is no
  1208. // data that's needed -- their method instances are all NULL and the module
  1209. // doesn't get included in the build
  1210. if (this != mContext->mScratchModule)
  1211. {
  1212. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1213. {
  1214. auto typeInst = mOwnedTypeInstances[typeIdx];
  1215. if (!typeInst->IsDeleting())
  1216. {
  1217. typeInst->mIsReified = mIsReified;
  1218. if (rebuildKind != BfModule::RebuildKind_None)
  1219. {
  1220. if (typeInst->IsOnDemand())
  1221. {
  1222. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1223. if (rebuildKind == BfModule::RebuildKind_All)
  1224. mContext->DeleteType(typeInst);
  1225. else
  1226. {
  1227. RebuildMethods(typeInst);
  1228. }
  1229. }
  1230. else
  1231. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1232. mContext->RebuildType(typeInst, false, false, true);
  1233. //mContext->RebuildType(typeInst, false, false, false);
  1234. }
  1235. else
  1236. {
  1237. auto _HandleMethod = [&](BfMethodInstance* methodInstance)
  1238. {
  1239. if ((methodInstance != NULL) && (methodInstance->mDeclModule != NULL))
  1240. methodInstance->mDeclModule = this;
  1241. };
  1242. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1243. {
  1244. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1245. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  1246. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  1247. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  1248. {
  1249. oldOnDemandCount++;
  1250. }
  1251. _HandleMethod(methodGroup.mDefault);
  1252. if (methodGroup.mMethodSpecializationMap != NULL)
  1253. for (auto& kv : *methodGroup.mMethodSpecializationMap)
  1254. _HandleMethod(kv.mValue);
  1255. }
  1256. }
  1257. if (typeInst->IsDeleting())
  1258. typeIdx--;
  1259. }
  1260. }
  1261. }
  1262. if (!mIsDeleting)
  1263. Init();
  1264. mOnDemandMethodCount += oldOnDemandCount;
  1265. VerifyOnDemandMethods();
  1266. }
  1267. void BfModule::StartExtension()
  1268. {
  1269. BF_ASSERT(!mIsModuleMutable);
  1270. BfLogSysM("Extension started of module %p\n", this);
  1271. mExtensionCount++;
  1272. if (mBfIRBuilder != NULL)
  1273. mPrevIRBuilders.push_back(mBfIRBuilder);
  1274. mBfIRBuilder = NULL;
  1275. mWantsIRIgnoreWrites = false;
  1276. mFuncReferences.Clear();
  1277. mClassVDataRefs.Clear();
  1278. mClassVDataExtRefs.Clear();
  1279. for (auto& kv : mTypeDataRefs)
  1280. kv.mValue = BfIRValue();
  1281. mDbgRawAllocDataRefs.Clear();
  1282. mStringCharPtrPool.Clear();
  1283. mStringObjectPool.Clear();
  1284. mStaticFieldRefs.Clear();
  1285. for (auto& kv : mInterfaceSlotRefs)
  1286. kv.mValue = BfIRValue();
  1287. for (auto& pairVal : mDeferredMethodCallData)
  1288. delete pairVal.mValue;
  1289. mDeferredMethodCallData.Clear();
  1290. mDeferredMethodIds.Clear();
  1291. DisownMethods();
  1292. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1293. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1294. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1295. Init(false);
  1296. if (!wasAwaitingInitFinish)
  1297. FinishInit();
  1298. mOnDemandMethodCount = prevOnDemandMethodCount;
  1299. }
  1300. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1301. {
  1302. auto hasObjectDebugFlags = mContext->mBfObjectType->mFieldInstances[0].mResolvedType->IsInteger();
  1303. BfIRValue vDataValue;
  1304. if (hasObjectDebugFlags)
  1305. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1306. else
  1307. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1308. typeValueParams.push_back(vDataValue);
  1309. if (hasObjectDebugFlags)
  1310. {
  1311. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1312. typeValueParams.push_back(GetDefaultValue(primType));
  1313. }
  1314. }
  1315. BfIRValue BfModule::GetConstValue(int64 val)
  1316. {
  1317. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1318. }
  1319. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1320. {
  1321. BfType* checkType = type;
  1322. if (type->IsTypedPrimitive())
  1323. {
  1324. checkType = type->GetUnderlyingType();
  1325. }
  1326. if (checkType->IsPrimitiveType())
  1327. {
  1328. auto primType = (BfPrimitiveType*)checkType;
  1329. if (checkType->IsFloat())
  1330. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1331. else
  1332. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1333. }
  1334. return BfIRValue();
  1335. }
  1336. BfIRValue BfModule::GetConstValue8(int val)
  1337. {
  1338. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1339. }
  1340. BfIRValue BfModule::GetConstValue32(int32 val)
  1341. {
  1342. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1343. }
  1344. BfIRValue BfModule::GetConstValue64(int64 val)
  1345. {
  1346. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1347. }
  1348. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1349. {
  1350. PopulateType(type, BfPopulateType_Data);
  1351. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1352. if (type->IsTypedPrimitive())
  1353. {
  1354. auto underlyingType = type->GetUnderlyingType();
  1355. if (underlyingType == NULL)
  1356. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1357. return GetDefaultValue(type->GetUnderlyingType());
  1358. }
  1359. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1360. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1361. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1362. if ((type->IsIntegral()) || (type->IsBoolean()))
  1363. {
  1364. auto primType = (BfPrimitiveType*)type;
  1365. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1366. }
  1367. if (type->IsFloat())
  1368. {
  1369. auto primType = (BfPrimitiveType*)type;
  1370. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1371. }
  1372. return mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(type));
  1373. }
  1374. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1375. {
  1376. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1377. if (type->mSize == 0)
  1378. return BfTypedValue(BfIRValue::sValueless, type);
  1379. else if (mBfIRBuilder != NULL)
  1380. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1381. else
  1382. return BfTypedValue(BfIRValue(BfIRValueFlags_Value, -1), type);
  1383. }
  1384. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1385. {
  1386. if (type->IsVar())
  1387. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1388. PopulateType(type, BfPopulateType_Data);
  1389. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1390. if (defaultValueKind == BfDefaultValueKind_Undef)
  1391. {
  1392. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(type)), type);
  1393. }
  1394. BfTypedValue typedValue;
  1395. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1396. {
  1397. if (type->IsRef())
  1398. {
  1399. BfRefType* refType = (BfRefType*)type;
  1400. BfType* underlyingType = refType->GetUnderlyingType();
  1401. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1402. }
  1403. else
  1404. {
  1405. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1406. }
  1407. if (!mBfIRBuilder->mIgnoreWrites)
  1408. {
  1409. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1410. GetConstValue(type->mSize), type->mAlign);
  1411. }
  1412. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1413. typedValue = LoadValue(typedValue);
  1414. return typedValue;
  1415. }
  1416. if ((type->IsRef()) && (!allowRef))
  1417. {
  1418. BfRefType* refType = (BfRefType*)type;
  1419. BfType* underlyingType = refType->GetUnderlyingType();
  1420. if (underlyingType->IsValuelessType())
  1421. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1422. else
  1423. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1424. }
  1425. else
  1426. {
  1427. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1428. }
  1429. return typedValue;
  1430. }
  1431. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1432. {
  1433. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1434. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1435. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1436. BfIRValue strConstant;
  1437. if (define)
  1438. {
  1439. strConstant = mBfIRBuilder->CreateConstString(str);
  1440. }
  1441. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1442. true, BfIRLinkageType_External,
  1443. strConstant, stringDataName);
  1444. if (define)
  1445. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1446. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1447. }
  1448. void BfModule::FixConstValueParams(BfTypeInstance* typeInst, SizedArrayImpl<BfIRValue>& valueParams, bool fillInPadding)
  1449. {
  1450. if ((!typeInst->mTypeDef->mIsCombinedPartial) && (!fillInPadding))
  1451. return;
  1452. int prevDataIdx = -1;
  1453. int usedDataIdx = 0;
  1454. int valueParamIdx = 0;
  1455. if (typeInst->mBaseType != NULL)
  1456. {
  1457. usedDataIdx++;
  1458. valueParamIdx++;
  1459. prevDataIdx++;
  1460. }
  1461. int startingParamsSize = (int)valueParams.mSize;
  1462. for (int fieldIdx = 0; fieldIdx < (int)typeInst->mFieldInstances.size(); fieldIdx++)
  1463. {
  1464. auto fieldInstance = &typeInst->mFieldInstances[fieldIdx];
  1465. if (fieldInstance->mDataIdx < 0)
  1466. continue;
  1467. BF_ASSERT(fieldInstance->mDataIdx > prevDataIdx);
  1468. if (fillInPadding)
  1469. {
  1470. for (int i = prevDataIdx + 1; i < fieldInstance->mDataIdx; i++)
  1471. valueParams.Insert(valueParamIdx++, mBfIRBuilder->CreateConstArrayZero(0));
  1472. }
  1473. valueParamIdx++;
  1474. prevDataIdx = fieldInstance->mDataIdx;
  1475. usedDataIdx++;
  1476. if (usedDataIdx <= valueParams.mSize)
  1477. continue;
  1478. valueParams.Add(GetDefaultValue(fieldInstance->mResolvedType));
  1479. }
  1480. }
  1481. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1482. {
  1483. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1484. mBfIRBuilder->PopulateType(stringTypeInst);
  1485. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1486. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1487. BfIRValue stringValData;
  1488. if (define)
  1489. {
  1490. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1491. mStringCharPtrPool[stringId] = stringCharsVal;
  1492. SizedArray<BfIRValue, 8> typeValueParams;
  1493. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1494. FixConstValueParams(stringTypeInst->mBaseType, typeValueParams);
  1495. auto objData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1496. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1497. typeValueParams.clear();
  1498. typeValueParams.push_back(objData);
  1499. if (lenByteCount == 4)
  1500. {
  1501. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1502. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1503. }
  1504. else
  1505. {
  1506. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1507. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1508. }
  1509. typeValueParams.push_back(stringCharsVal); // mPtr
  1510. FixConstValueParams(stringTypeInst, typeValueParams);
  1511. stringValData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1512. }
  1513. mBfIRBuilder->PopulateType(stringTypeInst);
  1514. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1515. mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full),
  1516. true,
  1517. BfIRLinkageType_External,
  1518. define ? stringValData : BfIRValue(),
  1519. stringObjName);
  1520. return stringValLiteral;
  1521. }
  1522. bool BfModule::HasStringId(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1523. {
  1524. if (constHolder == NULL)
  1525. constHolder = mBfIRBuilder;
  1526. auto constant = constHolder->GetConstant(constantStr);
  1527. if (constant == NULL)
  1528. return false;
  1529. while (constant->mConstType == BfConstType_BitCast)
  1530. {
  1531. auto constBitCast = (BfConstantBitCast*)constant;
  1532. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1533. }
  1534. if (constant->mTypeCode == BfTypeCode_StringId)
  1535. {
  1536. return true;
  1537. }
  1538. return false;
  1539. }
  1540. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1541. {
  1542. if (constHolder == NULL)
  1543. constHolder = mBfIRBuilder;
  1544. auto constant = constHolder->GetConstant(constantStr);
  1545. if (constant == NULL)
  1546. return -1;
  1547. if (constant->mTypeCode == BfTypeCode_StringId)
  1548. {
  1549. return constant->mInt32;
  1550. }
  1551. while (constant->mConstType == BfConstType_BitCast)
  1552. {
  1553. auto constBitCast = (BfConstantBitCast*)constant;
  1554. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1555. }
  1556. if (constant->mConstType == BfConstType_GEP32_2)
  1557. {
  1558. auto constGEP = (BfConstantGEP32_2*)constant;
  1559. constant = constHolder->GetConstantById(constGEP->mTarget);
  1560. }
  1561. if (constant->mConstType == BfConstType_GlobalVar)
  1562. {
  1563. auto constGV = (BfGlobalVar*)constant;
  1564. const char* strDataPrefix = "__bfStrData";
  1565. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1566. return atoi(constGV->mName + strlen(strDataPrefix));
  1567. const char* strObjPrefix = "__bfStrObj";
  1568. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1569. return atoi(constGV->mName + strlen(strObjPrefix));
  1570. }
  1571. return -1;
  1572. }
  1573. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1574. {
  1575. int strId = GetStringPoolIdx(constantStr, constHolder);
  1576. if (strId != -1)
  1577. {
  1578. auto& entry = mContext->mStringObjectIdMap[strId];
  1579. return &entry.mString;
  1580. }
  1581. return NULL;
  1582. }
  1583. CeDbgState* BfModule::GetCeDbgState()
  1584. {
  1585. if (!mIsComptimeModule)
  1586. return NULL;
  1587. if ((mCompiler->mCeMachine != NULL) && (mCompiler->mCeMachine->mDebugger != NULL))
  1588. return mCompiler->mCeMachine->mDebugger->mCurDbgState;
  1589. return NULL;
  1590. }
  1591. BfIRValue BfModule::GetStringCharPtr(int stringId, bool force)
  1592. {
  1593. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1594. {
  1595. mUnreifiedStringPoolRefs.Add(stringId);
  1596. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, stringId);
  1597. }
  1598. BfIRValue* irValue = NULL;
  1599. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1600. return *irValue;
  1601. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1602. if (!mStringObjectPool.ContainsKey(stringId))
  1603. mStringPoolRefs.Add(stringId);
  1604. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1605. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1606. *irValue = strCharPtrConst;
  1607. return strCharPtrConst;
  1608. }
  1609. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue, bool force)
  1610. {
  1611. if (strValue.IsConst())
  1612. {
  1613. int stringId = GetStringPoolIdx(strValue);
  1614. BF_ASSERT(stringId != -1);
  1615. return GetStringCharPtr(stringId, force);
  1616. }
  1617. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1618. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1619. return charPtr;
  1620. }
  1621. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str, bool force)
  1622. {
  1623. return GetStringCharPtr(GetStringObjectValue(str, force), force);
  1624. }
  1625. BfIRValue BfModule::GetStringObjectValue(int strId, bool define, bool force)
  1626. {
  1627. BfIRValue* objValue;
  1628. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1629. return *objValue;
  1630. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1631. return GetStringObjectValue(stringPoolEntry.mString, define, force);
  1632. }
  1633. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define, bool force)
  1634. {
  1635. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1636. mBfIRBuilder->PopulateType(stringType);
  1637. int strId = mContext->GetStringLiteralId(str);
  1638. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1639. {
  1640. auto refModule = this;
  1641. if ((this == mContext->mUnreifiedModule) && (mCurTypeInstance != NULL))
  1642. refModule = mCurTypeInstance->mModule;
  1643. refModule->mUnreifiedStringPoolRefs.Add(strId);
  1644. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, strId);
  1645. }
  1646. BfIRValue* irValuePtr = NULL;
  1647. if (mStringObjectPool.TryGetValue(strId, &irValuePtr))
  1648. return *irValuePtr;
  1649. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1650. if (!mStringCharPtrPool.ContainsKey(strId))
  1651. mStringPoolRefs.Add(strId);
  1652. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1653. mStringObjectPool[strId] = strObject;
  1654. mStringPoolRefs.Add(strId);
  1655. return strObject;
  1656. }
  1657. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1658. {
  1659. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1660. type,
  1661. true,
  1662. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1663. constant,
  1664. name.c_str());
  1665. return newConst;
  1666. }
  1667. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1668. {
  1669. auto curScope = mCurMethodState->mCurScope;
  1670. if (curScope->mLabelNode != NULL)
  1671. {
  1672. curScope->mLabelNode->ToString(curScope->mLabel);
  1673. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1674. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1675. auto autoComplete = mCompiler->GetAutoComplete();
  1676. if (autoComplete != NULL)
  1677. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1678. }
  1679. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1680. {
  1681. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1682. while (checkScope != NULL)
  1683. {
  1684. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1685. {
  1686. auto errorNode = Warn(0, StrFormat("Duplicate scope label '%s'", checkScope->mLabel.c_str()), curScope->mLabelNode);
  1687. if (errorNode != NULL)
  1688. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1689. break;
  1690. }
  1691. checkScope = checkScope->mPrevScope;
  1692. }
  1693. }
  1694. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1695. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1696. {
  1697. if (prevScope->mHadScopeValueRetain)
  1698. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1699. else
  1700. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1701. }
  1702. mCurMethodState->mBlockNestLevel++;
  1703. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1704. {
  1705. // DIScope could be NULL if we're in an unspecialized method (for example)
  1706. if (mCurMethodState->mCurScope->mDIScope)
  1707. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1708. }
  1709. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1710. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1711. mCurMethodState->mCurScope->mMixinState = mCurMethodState->mMixinState;
  1712. }
  1713. void BfModule::RestoreScoreState_LocalVariables(int localVarStart)
  1714. {
  1715. while (localVarStart < (int)mCurMethodState->mLocals.size())
  1716. {
  1717. auto localVar = mCurMethodState->mLocals.back();
  1718. LocalVariableDone(localVar, false);
  1719. mCurMethodState->mLocals.pop_back();
  1720. if (localVar->mShadowedLocal != NULL)
  1721. {
  1722. BfLocalVarEntry* localVarEntryPtr;
  1723. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1724. {
  1725. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1726. }
  1727. }
  1728. else
  1729. {
  1730. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1731. }
  1732. if (localVar->mIsBumpAlloc)
  1733. localVar->~BfLocalVariable();
  1734. else
  1735. delete localVar;
  1736. }
  1737. }
  1738. void BfModule::RestoreScopeState()
  1739. {
  1740. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1741. mCurMethodState->mBlockNestLevel--;
  1742. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1743. {
  1744. BfIRBlock afterEndBlock;
  1745. if (!mCurMethodState->mLeftBlockUncond)
  1746. {
  1747. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1748. mBfIRBuilder->CreateBr(afterEndBlock);
  1749. mBfIRBuilder->ClearDebugLocation_Last();
  1750. }
  1751. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1752. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1753. if (afterEndBlock)
  1754. {
  1755. mBfIRBuilder->AddBlock(afterEndBlock);
  1756. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1757. }
  1758. }
  1759. mCurMethodState->mCurScope->mDone = true;
  1760. if (!mCurMethodState->mLeftBlockUncond)
  1761. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1762. EmitDeferredCallProcessorInstances(mCurMethodState->mCurScope);
  1763. RestoreScoreState_LocalVariables(mCurMethodState->mCurScope->mLocalVarStart);
  1764. if (mCurMethodState->mCurScope->mValueScopeStart)
  1765. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1766. mCurMethodState->mCurScope = prevScopeData;
  1767. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1768. }
  1769. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1770. {
  1771. if (mBfIRBuilder->mIgnoreWrites)
  1772. return mBfIRBuilder->GetFakeVal();
  1773. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1774. mBfIRBuilder->PopulateType(type);
  1775. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1776. if (!mBfIRBuilder->mIgnoreWrites)
  1777. BF_ASSERT(!prevInsertBlock.IsFake());
  1778. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1779. BfIRValue allocaInst;
  1780. if (arraySize)
  1781. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1782. else
  1783. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1784. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1785. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1786. if (name != NULL)
  1787. mBfIRBuilder->SetName(allocaInst, name);
  1788. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1789. if ((addLifetime) && (WantsLifetimes()))
  1790. {
  1791. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1792. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1793. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1794. }
  1795. return allocaInst;
  1796. }
  1797. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1798. {
  1799. if (mBfIRBuilder->mIgnoreWrites)
  1800. return mBfIRBuilder->GetFakeVal();
  1801. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1802. mBfIRBuilder->PopulateType(typeInst);
  1803. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1804. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1805. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1806. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1807. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1808. if (name != NULL)
  1809. mBfIRBuilder->SetName(allocaInst, name);
  1810. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1811. if ((addLifetime) && (WantsLifetimes()))
  1812. {
  1813. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1814. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1815. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1816. }
  1817. return allocaInst;
  1818. }
  1819. BfDeferredCallEntry* BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape, BfIRBlock valBlock)
  1820. {
  1821. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1822. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1823. /*if (mCurMethodState->mInHeadScope)
  1824. isScopeAlloc = true;*/
  1825. if (scopeData == NULL)
  1826. return NULL;
  1827. auto checkBaseType = val.mType->ToTypeInstance();
  1828. if ((checkBaseType != NULL) && (checkBaseType->IsObject()) && (!arraySize))
  1829. {
  1830. bool hadDtorCall = false;
  1831. while (checkBaseType != NULL)
  1832. {
  1833. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  1834. if (dtorMethodDef != NULL)
  1835. {
  1836. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  1837. if (dtorMethodInstance)
  1838. {
  1839. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1840. BfIRValue useVal = val.mValue;
  1841. BfIRBlock prevBlock = mBfIRBuilder->GetInsertBlock();
  1842. if (valBlock)
  1843. mBfIRBuilder->SetInsertPoint(valBlock);
  1844. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1845. if (!useVal.IsConst())
  1846. mBfIRBuilder->ClearDebugLocation(useVal);
  1847. if (valBlock)
  1848. mBfIRBuilder->SetInsertPoint(prevBlock);
  1849. if (isDynAlloc)
  1850. {
  1851. //
  1852. }
  1853. else if (condAlloca)
  1854. {
  1855. BF_ASSERT(!IsTargetingBeefBackend());
  1856. BF_ASSERT(!isDynAlloc);
  1857. auto valPtr = CreateAlloca(checkBaseType);
  1858. mBfIRBuilder->ClearDebugLocation_Last();
  1859. mBfIRBuilder->CreateAlignedStore(useVal, valPtr, checkBaseType->mAlign);
  1860. mBfIRBuilder->ClearDebugLocation_Last();
  1861. useVal = valPtr;
  1862. }
  1863. SizedArray<BfIRValue, 1> llvmArgs;
  1864. llvmArgs.push_back(useVal);
  1865. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1866. if (deferredCall != NULL)
  1867. {
  1868. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1869. if (condAlloca)
  1870. deferredCall->mArgsNeedLoad = true;
  1871. }
  1872. hadDtorCall = true;
  1873. break;
  1874. }
  1875. }
  1876. checkBaseType = checkBaseType->mBaseType;
  1877. }
  1878. return NULL;
  1879. }
  1880. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1881. if (mayEscape)
  1882. {
  1883. if ((!IsOptimized()) && (!mIsComptimeModule) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1884. {
  1885. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1886. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1887. if (!isDyn)
  1888. {
  1889. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1890. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1891. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1892. if (!dtorMethodInstance.mMethodInstance)
  1893. {
  1894. Fail(StrFormat("Unable to find %s", methodName));
  1895. }
  1896. else
  1897. {
  1898. SizedArray<BfIRValue, 1> llvmArgs;
  1899. if (IsTargetingBeefBackend())
  1900. {
  1901. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1902. //mBfIRBuilder->ClearDebugLocation_Last();
  1903. }
  1904. else
  1905. llvmArgs.push_back(val.mValue);
  1906. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1907. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1908. if (arraySize)
  1909. llvmArgs.push_back(arraySize);
  1910. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1911. }
  1912. }
  1913. else
  1914. {
  1915. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1916. {
  1917. BfIRValue clearSize = arraySize;
  1918. if (val.mType->GetStride() > 1)
  1919. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1920. const char* methodName = "SetDeletedX";
  1921. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1922. BF_ASSERT(dtorMethodInstance);
  1923. if (!dtorMethodInstance)
  1924. {
  1925. Fail(StrFormat("Unable to find %s", methodName));
  1926. }
  1927. else
  1928. {
  1929. SizedArray<BfIRValue, 1> llvmArgs;
  1930. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1931. //mBfIRBuilder->ClearDebugLocation_Last();
  1932. llvmArgs.push_back(clearSize);
  1933. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1934. }
  1935. }
  1936. else
  1937. {
  1938. intptr clearSize = val.mType->mSize;
  1939. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1940. if (constant != NULL)
  1941. clearSize = (intptr)(clearSize * constant->mInt64);
  1942. const char* funcName = "SetDeleted1";
  1943. if (clearSize >= 16)
  1944. funcName = "SetDeleted16";
  1945. else if (clearSize >= 8)
  1946. funcName = "SetDeleted8";
  1947. else if (clearSize >= 4)
  1948. funcName = "SetDeleted4";
  1949. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1950. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1951. if (!dtorMethodInstance)
  1952. {
  1953. Fail(StrFormat("Unable to find %s", funcName));
  1954. }
  1955. else
  1956. {
  1957. SizedArray<BfIRValue, 1> llvmArgs;
  1958. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1959. //mBfIRBuilder->ClearDebugLocation_Last();
  1960. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1961. }
  1962. }
  1963. }
  1964. }
  1965. }
  1966. return NULL;
  1967. }
  1968. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1969. {
  1970. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1971. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1972. return false;
  1973. auto checkTypeInstance = startTypeInstance;
  1974. while (checkTypeInstance != NULL)
  1975. {
  1976. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1977. {
  1978. if (fieldInstance.mMergedDataIdx != -1)
  1979. {
  1980. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1981. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1982. {
  1983. // For fields added in extensions, we automatically initialize those if necessary
  1984. auto fieldDef = fieldInstance.GetFieldDef();
  1985. if (!fieldDef->mDeclaringType->IsExtension())
  1986. return false;
  1987. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  1988. {
  1989. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1990. mBfIRBuilder->SaveDebugLocation();
  1991. if (localVar->IsParam())
  1992. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1993. else
  1994. {
  1995. BF_ASSERT(localVar->mDeclBlock);
  1996. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1997. }
  1998. mBfIRBuilder->ClearDebugLocation();
  1999. BfIRValue curVal;
  2000. if (localVar->mIsThis)
  2001. curVal = mBfIRBuilder->GetArgument(0);
  2002. else
  2003. curVal = localVar->mAddr;
  2004. auto subTypeInstance = startTypeInstance;
  2005. while (subTypeInstance != checkTypeInstance)
  2006. {
  2007. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  2008. subTypeInstance = subTypeInstance->mBaseType;
  2009. }
  2010. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  2011. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  2012. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  2013. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  2014. mBfIRBuilder->RestoreDebugLocation();
  2015. }
  2016. localVar->mUnassignedFieldFlags &= ~checkMask;
  2017. if (localVar->mUnassignedFieldFlags == 0)
  2018. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2019. }
  2020. }
  2021. }
  2022. checkTypeInstance = checkTypeInstance->mBaseType;
  2023. }
  2024. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  2025. }
  2026. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  2027. {
  2028. BfAstNode* localNameNode = localVar->mNameNode;
  2029. if ((localVar->mIsThis) && (mCurMethodInstance != NULL))
  2030. {
  2031. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  2032. }
  2033. if (localNameNode != NULL)
  2034. {
  2035. bool isOut = false;
  2036. if (localVar->mResolvedType->IsRef())
  2037. {
  2038. auto refType = (BfRefType*)localVar->mResolvedType;
  2039. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  2040. }
  2041. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  2042. {
  2043. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  2044. TryLocalVariableInit(localVar);
  2045. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  2046. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  2047. // We may have init blocks that we aren't processing here...
  2048. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  2049. deferFullAnalysis = true;
  2050. //bool deferFullAnalysis = true;
  2051. bool deferUsageWarning = deferFullAnalysis && (mCompiler->IsAutocomplete()) &&
  2052. (mCompiler->mResolvePassData->mAutoComplete->mResolveType != BfResolveType_GetFixits);
  2053. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  2054. (!localVar->mIsImplicitParam))
  2055. {
  2056. if (deferUsageWarning)
  2057. {
  2058. // Ignore
  2059. }
  2060. else if (localVar->mIsThis)
  2061. {
  2062. bool foundFields = false;
  2063. auto checkTypeInstance = mCurTypeInstance;
  2064. while (checkTypeInstance != NULL)
  2065. {
  2066. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  2067. {
  2068. if (fieldInstance.mMergedDataIdx == -1)
  2069. continue;
  2070. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  2071. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  2072. {
  2073. auto fieldDef = fieldInstance.GetFieldDef();
  2074. if (mCurMethodInstance->mMethodDef->mDeclaringType->mIsPartial)
  2075. {
  2076. if (mCurMethodInstance->mMethodDef->mDeclaringType != fieldInstance.GetFieldDef()->mDeclaringType)
  2077. {
  2078. // This extension is only responsible for its own fields
  2079. foundFields = true;
  2080. continue;
  2081. }
  2082. if (fieldDef->GetInitializer() != NULL)
  2083. {
  2084. // This initializer was handled in CtorNoBody
  2085. foundFields = true;
  2086. continue;
  2087. }
  2088. }
  2089. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  2090. {
  2091. String propName;
  2092. if (propertyDeclaration->mNameNode != NULL)
  2093. propertyDeclaration->mNameNode->ToString(propName);
  2094. if (checkTypeInstance == mCurTypeInstance)
  2095. {
  2096. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  2097. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2098. }
  2099. else
  2100. {
  2101. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  2102. TypeToString(checkTypeInstance).c_str(),
  2103. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2104. }
  2105. }
  2106. else
  2107. {
  2108. if (checkTypeInstance == mCurTypeInstance)
  2109. {
  2110. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  2111. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2112. }
  2113. else
  2114. {
  2115. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  2116. TypeToString(checkTypeInstance).c_str(),
  2117. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2118. }
  2119. }
  2120. foundFields = true;
  2121. }
  2122. }
  2123. checkTypeInstance = checkTypeInstance->mBaseType;
  2124. }
  2125. if (!foundFields)
  2126. {
  2127. if (mCurTypeInstance->mInstSize > 0)
  2128. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  2129. }
  2130. }
  2131. else if (localVar->IsParam())
  2132. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  2133. else if (!deferUsageWarning)
  2134. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2135. }
  2136. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  2137. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2138. }
  2139. }
  2140. }
  2141. void BfModule::CreateRetValLocal()
  2142. {
  2143. if (mCurMethodState->mRetVal)
  2144. {
  2145. BfLocalVariable* localDef = new BfLocalVariable();
  2146. localDef->mName = "return";
  2147. localDef->mResolvedType = mCurMethodState->mRetVal.mType;
  2148. localDef->mAddr = mCurMethodState->mRetVal.mValue;
  2149. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2150. AddLocalVariableDef(localDef);
  2151. }
  2152. else if (mCurMethodState->mRetValAddr)
  2153. {
  2154. BfLocalVariable* localDef = new BfLocalVariable();
  2155. localDef->mName = "return";
  2156. localDef->mResolvedType = CreateRefType(mCurMethodInstance->mReturnType);
  2157. localDef->mAddr = mCurMethodState->mRetValAddr;
  2158. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2159. AddLocalVariableDef(localDef);
  2160. }
  2161. }
  2162. void BfModule::MarkDynStack(BfScopeData* scopeData)
  2163. {
  2164. auto checkScope = mCurMethodState->mCurScope;
  2165. while (true)
  2166. {
  2167. if (checkScope == scopeData)
  2168. break;
  2169. checkScope->mHadOuterDynStack = true;
  2170. checkScope = checkScope->mPrevScope;
  2171. }
  2172. }
  2173. void BfModule::SaveStackState(BfScopeData* scopeData)
  2174. {
  2175. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  2176. // scopes within scopeData restore the stack
  2177. auto checkScope = mCurMethodState->mCurScope;
  2178. while (true)
  2179. {
  2180. if (checkScope == scopeData)
  2181. {
  2182. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  2183. {
  2184. if (mBfIRBuilder->mHasDebugInfo)
  2185. mBfIRBuilder->SaveDebugLocation();
  2186. auto prevPos = mBfIRBuilder->GetInsertBlock();
  2187. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  2188. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  2189. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  2190. mBfIRBuilder->SetInsertPoint(prevPos);
  2191. if (mBfIRBuilder->mHasDebugInfo)
  2192. mBfIRBuilder->RestoreDebugLocation();
  2193. }
  2194. break;
  2195. }
  2196. if (checkScope->mSavedStack)
  2197. {
  2198. for (auto usage : checkScope->mSavedStackUses)
  2199. mBfIRBuilder->EraseInstFromParent(usage);
  2200. checkScope->mSavedStackUses.Clear();
  2201. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  2202. checkScope->mSavedStack = BfIRValue();
  2203. }
  2204. checkScope = checkScope->mPrevScope;
  2205. }
  2206. }
  2207. BfIRValue BfModule::ValueScopeStart()
  2208. {
  2209. if (IsTargetingBeefBackend())
  2210. return mBfIRBuilder->CreateValueScopeStart();
  2211. return BfIRValue();
  2212. }
  2213. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  2214. {
  2215. if (valueScopeStart)
  2216. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  2217. }
  2218. BfProjectSet* BfModule::GetVisibleProjectSet()
  2219. {
  2220. if (mCurMethodState == NULL)
  2221. return NULL;
  2222. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  2223. {
  2224. HashSet<BfType*> seenTypes;
  2225. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  2226. {
  2227. if (mCurMethodState->mVisibleProjectSet.Add(project))
  2228. {
  2229. for (auto dep : project->mDependencies)
  2230. _AddProject(dep);
  2231. }
  2232. };
  2233. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  2234. {
  2235. auto typeInstance = type->ToTypeInstance();
  2236. if (typeInstance == NULL)
  2237. {
  2238. if (type->IsSizedArray())
  2239. _AddType(type->GetUnderlyingType());
  2240. return;
  2241. }
  2242. if (typeInstance->IsTuple())
  2243. {
  2244. for (auto& fieldInst : typeInstance->mFieldInstances)
  2245. {
  2246. if (fieldInst.mDataIdx != -1)
  2247. _AddType(fieldInst.mResolvedType);
  2248. }
  2249. }
  2250. _AddProject(typeInstance->mTypeDef->mProject);
  2251. if (typeInstance->mGenericTypeInfo == NULL)
  2252. return;
  2253. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2254. {
  2255. if (seenTypes.Add(type))
  2256. _AddType(type);
  2257. }
  2258. };
  2259. if (mCurTypeInstance != NULL)
  2260. _AddType(mCurTypeInstance);
  2261. auto methodState = mCurMethodState;
  2262. while (methodState != NULL)
  2263. {
  2264. if (methodState->mMethodInstance != NULL)
  2265. {
  2266. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  2267. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  2268. {
  2269. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2270. _AddType(type);
  2271. }
  2272. }
  2273. methodState = methodState->mPrevMethodState;
  2274. }
  2275. }
  2276. return &mCurMethodState->mVisibleProjectSet;
  2277. }
  2278. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2279. {
  2280. auto bfParser = astNode->GetSourceData()->ToParserData();
  2281. if (bfParser == NULL)
  2282. return NULL;
  2283. BfFileInstance** fileInstancePtr = NULL;
  2284. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2285. {
  2286. return *fileInstancePtr;
  2287. }
  2288. else
  2289. {
  2290. // It's possible two parsers have the same file name (ie: mNextRevision)
  2291. BfFileInstance** namedFileInstancePtr = NULL;
  2292. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2293. {
  2294. auto bfFileInstance = *namedFileInstancePtr;
  2295. *fileInstancePtr = bfFileInstance;
  2296. return bfFileInstance;
  2297. }
  2298. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2299. auto bfFileInstance = new BfFileInstance();
  2300. *fileInstancePtr = bfFileInstance;
  2301. *namedFileInstancePtr = bfFileInstance;
  2302. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2303. bfFileInstance->mParser = bfParser;
  2304. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2305. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasLineInfo()))
  2306. {
  2307. String fileName = bfParser->mFileName;
  2308. for (int i = 0; i < (int)fileName.length(); i++)
  2309. {
  2310. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2311. fileName[i] = DIR_SEP_CHAR;
  2312. }
  2313. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, BF_MAX(slashPos, 0)), bfParser->mMD5Hash);
  2314. }
  2315. return bfFileInstance;
  2316. }
  2317. }
  2318. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2319. {
  2320. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2321. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2322. return;
  2323. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2324. if (astNode == NULL)
  2325. return;
  2326. auto bfParser = astNode->GetSourceData()->ToParserData();
  2327. if (bfParser == NULL)
  2328. return;
  2329. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2330. {
  2331. if (mCurFilePosition.mFileInstance != NULL)
  2332. {
  2333. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2334. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2335. }
  2336. auto bfFileInstance = GetFileFromNode(astNode);
  2337. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2338. {
  2339. mCurFilePosition = bfFileInstance->mPrevPosition;
  2340. }
  2341. else
  2342. {
  2343. mCurFilePosition.mFileInstance = bfFileInstance;
  2344. mCurFilePosition.mCurLine = 0;
  2345. mCurFilePosition.mCurColumn = 0;
  2346. mCurFilePosition.mCurSrcPos = 0;
  2347. }
  2348. }
  2349. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2350. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2351. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2352. if (jumpEntry->mCharIdx > srcPos)
  2353. jumpEntry--;
  2354. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2355. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2356. mCurFilePosition.mCurColumn = 0;
  2357. while (mCurFilePosition.mCurSrcPos < srcPos)
  2358. {
  2359. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2360. {
  2361. mCurFilePosition.mCurLine++;
  2362. mCurFilePosition.mCurColumn = 0;
  2363. }
  2364. else
  2365. {
  2366. mCurFilePosition.mCurColumn++;
  2367. }
  2368. mCurFilePosition.mCurSrcPos++;
  2369. }
  2370. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2371. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasLineInfo()) && (mCurMethodState != NULL))
  2372. {
  2373. int column = mCurFilePosition.mCurColumn + 1;
  2374. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2375. {
  2376. // Set to illegal position
  2377. column = 0;
  2378. }
  2379. if (mSetIllegalSrcPosition)
  2380. column = 0;
  2381. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2382. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2383. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2384. {
  2385. // This is from a different scope...
  2386. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2387. {
  2388. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2389. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2390. }
  2391. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2392. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2393. }
  2394. else
  2395. {
  2396. if (mCurMethodState->mCurScope->mAltDIFile)
  2397. {
  2398. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2399. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2400. }
  2401. }
  2402. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2403. if (mCurMethodState->mCrossingMixin)
  2404. inlineAt = BfIRMDNode();
  2405. if ((!useDIScope) && (mIsComptimeModule))
  2406. useDIScope = wantDIFile;
  2407. if (!useDIScope)
  2408. mBfIRBuilder->ClearDebugLocation();
  2409. else
  2410. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2411. if ((flags & BfSrcPosFlag_Expression) == 0)
  2412. mBfIRBuilder->CreateStatementStart();
  2413. }
  2414. }
  2415. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2416. {
  2417. // We've turned off expr src pos (for now?)
  2418. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2419. }
  2420. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2421. {
  2422. if (mCompiler->mBfObjectTypeDef != NULL)
  2423. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2424. SetIllegalSrcPos();
  2425. }
  2426. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2427. {
  2428. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2429. {
  2430. auto curScope = mCurMethodState->mCurScope->mDIScope;
  2431. if (curScope)
  2432. {
  2433. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2434. {
  2435. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2436. mBfIRBuilder->SetCurrentDebugLocation(0, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2437. }
  2438. else
  2439. {
  2440. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2441. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2442. }
  2443. }
  2444. if ((flags & BfSrcPosFlag_Expression) == 0)
  2445. mBfIRBuilder->CreateStatementStart();
  2446. }
  2447. }
  2448. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2449. {
  2450. // We've turned off expr src pos (for now?)
  2451. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2452. }
  2453. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2454. {
  2455. if ((protection == BfProtection_Public) ||
  2456. (((protection == BfProtection_Protected) || (protection == BfProtection_ProtectedInternal)) && (allowProtected)) ||
  2457. ((protection == BfProtection_Private) && (allowPrivate)))
  2458. return true;
  2459. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2460. {
  2461. mAttributeState->mUsed = true;
  2462. return true;
  2463. }
  2464. if (((protection == BfProtection_Internal) || (protection == BfProtection_ProtectedInternal)) && (checkType != NULL))
  2465. {
  2466. if (CheckInternalProtection(checkType))
  2467. return true;
  2468. }
  2469. return false;
  2470. }
  2471. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2472. {
  2473. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2474. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2475. {
  2476. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2477. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2478. }
  2479. allowProtected = allowPrivate;
  2480. }
  2481. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2482. {
  2483. if (memberProtection == BfProtection_Hidden)
  2484. return false;
  2485. if (memberProtection == BfProtection_Public)
  2486. return true;
  2487. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2488. {
  2489. BfTypeInstance* curCheckType = mCurTypeInstance;
  2490. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2491. {
  2492. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2493. curCheckType = mixinOwner;
  2494. }
  2495. bool allowPrivate = (curCheckType != NULL) && (memberOwner->IsInstanceOf(curCheckType->mTypeDef));
  2496. if (curCheckType != NULL)
  2497. {
  2498. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2499. if (memberOwner->mTypeDef->IsGlobalsContainer())
  2500. allowPrivate |= curCheckType->mTypeDef->mNamespace == memberOwner->mTypeDef->mNamespace;
  2501. }
  2502. if (allowPrivate)
  2503. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2504. else
  2505. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2506. }
  2507. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2508. return true;
  2509. if ((memberProtection == BfProtection_Protected) || (memberProtection == BfProtection_ProtectedInternal))
  2510. {
  2511. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2512. {
  2513. bool allowProtected = false;
  2514. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2515. auto curCheckType = mCurTypeInstance;
  2516. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2517. {
  2518. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2519. curCheckType = mixinOwner;
  2520. }
  2521. if ((flags & BfProtectionCheckFlag_InstanceLookup) != 0)
  2522. {
  2523. auto lookupCheckType = lookupStartType;
  2524. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2525. {
  2526. if (lookupCheckType == curCheckType)
  2527. {
  2528. allowProtected = true;
  2529. break;
  2530. }
  2531. if (lookupCheckType == memberOwner)
  2532. break;
  2533. lookupCheckType = lookupCheckType->mBaseType;
  2534. if (lookupCheckType == NULL)
  2535. break;
  2536. }
  2537. }
  2538. else
  2539. {
  2540. auto lookupCheckType = curCheckType;
  2541. while (lookupCheckType->mInheritDepth >= memberOwner->mInheritDepth)
  2542. {
  2543. if (lookupCheckType == memberOwner)
  2544. {
  2545. allowProtected = true;
  2546. break;
  2547. }
  2548. lookupCheckType = lookupCheckType->mBaseType;
  2549. if (lookupCheckType == NULL)
  2550. break;
  2551. }
  2552. }
  2553. if (!allowProtected)
  2554. {
  2555. // It's possible our outer type is derived from 'memberOwner'
  2556. while (curCheckType->mTypeDef->mNestDepth > 0)
  2557. {
  2558. curCheckType = GetOuterType(curCheckType);
  2559. if (curCheckType == NULL)
  2560. break;
  2561. auto lookupCheckType = lookupStartType;
  2562. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2563. {
  2564. if (lookupCheckType == curCheckType)
  2565. {
  2566. allowProtected = true;
  2567. break;
  2568. }
  2569. if (lookupCheckType == memberOwner)
  2570. break;
  2571. lookupCheckType = lookupCheckType->mBaseType;
  2572. if (lookupCheckType == NULL)
  2573. break;
  2574. }
  2575. }
  2576. }
  2577. if (allowProtected)
  2578. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2579. else
  2580. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2581. }
  2582. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2583. return true;
  2584. }
  2585. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2586. {
  2587. mAttributeState->mUsed = true;
  2588. return true;
  2589. }
  2590. if (((memberProtection == BfProtection_Internal) || (memberProtection == BfProtection_ProtectedInternal)) && (memberOwner != NULL))
  2591. {
  2592. if (CheckInternalProtection(memberOwner->mTypeDef))
  2593. return true;
  2594. }
  2595. return false;
  2596. }
  2597. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2598. {
  2599. if (mCompiler->mResolvePassData != NULL)
  2600. {
  2601. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2602. sourceClassifier->SetElementType(astNode, elementType);
  2603. }
  2604. }
  2605. bool BfModule::PreFail()
  2606. {
  2607. if (!mIgnoreErrors)
  2608. return true;
  2609. SetFail();
  2610. return false;
  2611. }
  2612. void BfModule::SetFail()
  2613. {
  2614. if (mIgnoreErrors)
  2615. {
  2616. if (mAttributeState != NULL)
  2617. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2618. }
  2619. }
  2620. void BfModule::VerifyOnDemandMethods()
  2621. {
  2622. #ifdef _DEBUG
  2623. // if (mParentModule != NULL)
  2624. // {
  2625. // BF_ASSERT(mOnDemandMethodCount == 0);
  2626. // mParentModule->VerifyOnDemandMethods();
  2627. // return;
  2628. // }
  2629. //
  2630. // int onDemandCount = 0;
  2631. // for (auto type : mOwnedTypeInstances)
  2632. // {
  2633. // auto typeInst = type->ToTypeInstance();
  2634. // for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  2635. // {
  2636. // if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  2637. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  2638. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  2639. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  2640. // onDemandCount++;
  2641. // }
  2642. // }
  2643. //
  2644. // BF_ASSERT(mOnDemandMethodCount == onDemandCount);
  2645. #endif
  2646. }
  2647. bool BfModule::IsSkippingExtraResolveChecks()
  2648. {
  2649. if (mIsComptimeModule)
  2650. return false;
  2651. return mCompiler->IsSkippingExtraResolveChecks();
  2652. }
  2653. bool BfModule::AddErrorContext(StringImpl& errorString, BfAstNode* refNode, BfWhileSpecializingFlags& isWhileSpecializing, bool isWarning)
  2654. {
  2655. bool isWhileSpecializingMethod = false;
  2656. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2657. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2658. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2659. errorString += StrFormat("\n while generating append size calculating method");
  2660. else if (refNode == NULL)
  2661. {
  2662. if (mCurTypeInstance != NULL)
  2663. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2664. else if (mProject != NULL)
  2665. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2666. }
  2667. if (mCurTypeInstance != NULL)
  2668. {
  2669. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2670. {
  2671. // Propogate the fail all the way to the main method (assuming we're in a local method or lambda)
  2672. if (isWarning)
  2673. methodInstance->mHasWarning = true;
  2674. else
  2675. methodInstance->mHasFailed = true;
  2676. if (!methodInstance->mHasStartedDeclaration)
  2677. StartMethodDeclaration(methodInstance, NULL);
  2678. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2679. if (isSpecializedMethod)
  2680. {
  2681. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2682. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2683. if (unspecializedMethod == methodInstance)
  2684. {
  2685. // This is a local method inside a generic method
  2686. BF_ASSERT(methodInstance->mMethodDef->mIsLocalMethod);
  2687. }
  2688. else
  2689. {
  2690. if (isWarning)
  2691. {
  2692. if (unspecializedMethod->mHasWarning)
  2693. return false; // At least SOME error has already been reported
  2694. }
  2695. else
  2696. {
  2697. if (unspecializedMethod->mHasFailed)
  2698. return false; // At least SOME error has already been reported
  2699. }
  2700. }
  2701. }
  2702. if (isSpecializedMethod)
  2703. {
  2704. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2705. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2706. isWhileSpecializingMethod = true;
  2707. }
  2708. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2709. {
  2710. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2711. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2712. isWhileSpecializingMethod = true;
  2713. }
  2714. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2715. {
  2716. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2717. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2718. }
  2719. return true;
  2720. };
  2721. bool hadMethodInstance = false;
  2722. if (mCurMethodState != NULL)
  2723. {
  2724. auto checkMethodState = mCurMethodState;
  2725. while (checkMethodState != NULL)
  2726. {
  2727. auto methodInstance = checkMethodState->mMethodInstance;
  2728. if (methodInstance == NULL)
  2729. {
  2730. checkMethodState = checkMethodState->mPrevMethodState;
  2731. continue;
  2732. }
  2733. hadMethodInstance = true;
  2734. if (!_CheckMethodInstance(methodInstance))
  2735. return false;
  2736. checkMethodState = checkMethodState->mPrevMethodState;
  2737. }
  2738. }
  2739. if ((!hadMethodInstance) && (mCurMethodInstance != NULL))
  2740. {
  2741. if (!_CheckMethodInstance(mCurMethodInstance))
  2742. return false;
  2743. }
  2744. }
  2745. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2746. {
  2747. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2748. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2749. }
  2750. return true;
  2751. }
  2752. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent, bool deferError)
  2753. {
  2754. BP_ZONE("BfModule::Fail");
  2755. if (mIgnoreErrors)
  2756. {
  2757. mHadIgnoredError = true;
  2758. if (mAttributeState != NULL)
  2759. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2760. return NULL;
  2761. }
  2762. if (!mReportErrors)
  2763. {
  2764. mCompiler->mPassInstance->SilentFail();
  2765. return NULL;
  2766. }
  2767. if (refNode != NULL)
  2768. refNode = BfNodeToNonTemporary(refNode);
  2769. //BF_ASSERT(refNode != NULL);
  2770. if (mIsComptimeModule)
  2771. {
  2772. if (auto ceDbgState = GetCeDbgState())
  2773. {
  2774. // Follow normal fail path
  2775. }
  2776. else
  2777. {
  2778. mHadBuildError = true;
  2779. if ((mCompiler->mCeMachine->mCurContext != NULL) && (mCompiler->mCeMachine->mCurContext->mCurCallSource != NULL) &&
  2780. (mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode != NULL))
  2781. {
  2782. BfError* bfError = mCompiler->mPassInstance->Fail("Comptime method generation had errors",
  2783. mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode);
  2784. if (bfError != NULL)
  2785. mCompiler->mPassInstance->MoreInfo(error, refNode);
  2786. return bfError;
  2787. }
  2788. return NULL;
  2789. }
  2790. }
  2791. if ((mCurMethodState != NULL) && (mCurMethodState->mConstResolveState != NULL) && (mCurMethodState->mConstResolveState->mInCalcAppend))
  2792. {
  2793. mCurMethodState->mConstResolveState->mFailed = true;
  2794. return NULL;
  2795. }
  2796. if (mCurMethodInstance != NULL)
  2797. mCurMethodInstance->mHasFailed = true;
  2798. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2799. return NULL;
  2800. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2801. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2802. if (!mHadBuildError)
  2803. mHadBuildError = true;
  2804. if (mParentModule != NULL)
  2805. mParentModule->mHadBuildError = true;
  2806. if (mCurTypeInstance != NULL)
  2807. AddFailType(mCurTypeInstance);
  2808. BfLogSysM("BfModule::Fail module %p type %p %s @ %s\n", this, mCurTypeInstance, error.c_str(), (refNode != NULL) ? refNode->LocationToString().c_str() : "???");
  2809. String errorString = error;
  2810. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2811. if (!AddErrorContext(errorString, refNode, isWhileSpecializing, false))
  2812. return NULL;
  2813. BfError* bfError = NULL;
  2814. if (isWhileSpecializing)
  2815. deferError = true;
  2816. if (!mHadBuildError)
  2817. mHadBuildError = true;
  2818. // Check mixins
  2819. {
  2820. auto checkMethodState = mCurMethodState;
  2821. while (checkMethodState != NULL)
  2822. {
  2823. auto rootMixinState = checkMethodState->GetRootMixinState();
  2824. if (rootMixinState != NULL)
  2825. {
  2826. String mixinErr = StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str());
  2827. if (deferError)
  2828. bfError = mCompiler->mPassInstance->DeferFail(mixinErr, rootMixinState->mSource);
  2829. else
  2830. bfError = mCompiler->mPassInstance->Fail(mixinErr, rootMixinState->mSource);
  2831. if (bfError == NULL)
  2832. return NULL;
  2833. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2834. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2835. auto mixinState = checkMethodState->mMixinState;
  2836. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2837. {
  2838. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2839. mixinState = mixinState->mPrevMixinState;
  2840. }
  2841. return bfError;
  2842. }
  2843. checkMethodState = checkMethodState->mPrevMethodState;
  2844. }
  2845. }
  2846. if (deferError)
  2847. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2848. else if (refNode == NULL)
  2849. bfError = mCompiler->mPassInstance->Fail(errorString);
  2850. else
  2851. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2852. if (bfError != NULL)
  2853. {
  2854. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2855. bfError->mProject = mProject;
  2856. bfError->mIsPersistent = isPersistent;
  2857. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2858. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2859. else if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2860. mCompiler->mPassInstance->MoreInfo("Error in emitted code", mCurMethodState->mEmitRefNode);
  2861. }
  2862. return bfError;
  2863. }
  2864. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2865. {
  2866. if (mHadBuildError)
  2867. return NULL;
  2868. return Fail(error, refNode);
  2869. }
  2870. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2871. {
  2872. if (mIgnoreErrors)
  2873. return NULL;
  2874. if (refNode != NULL)
  2875. refNode = BfNodeToNonTemporary(refNode);
  2876. mHadBuildError = true;
  2877. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2878. if (bfError != NULL)
  2879. bfError->mProject = mProject;
  2880. return bfError;
  2881. }
  2882. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent, bool showInSpecialized)
  2883. {
  2884. if (mIgnoreErrors || mIgnoreWarnings)
  2885. return NULL;
  2886. if (!mReportErrors)
  2887. {
  2888. mCompiler->mPassInstance->SilentFail();
  2889. return NULL;
  2890. }
  2891. BfAstNode* unwarnNode = refNode;
  2892. //
  2893. {
  2894. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2895. while (parentNodeEntry != NULL)
  2896. {
  2897. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2898. break;
  2899. unwarnNode = parentNodeEntry->mNode;
  2900. parentNodeEntry = parentNodeEntry->mPrev;
  2901. }
  2902. }
  2903. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2904. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2905. {
  2906. return NULL;
  2907. }
  2908. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2909. if (mCurMethodInstance != NULL)
  2910. {
  2911. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2912. {
  2913. if (!showInSpecialized)
  2914. return NULL;
  2915. }
  2916. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2917. return NULL; // No ctorCalcAppend warnings
  2918. }
  2919. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2920. {
  2921. if (!showInSpecialized)
  2922. return NULL;
  2923. }
  2924. if (refNode != NULL)
  2925. refNode = BfNodeToNonTemporary(refNode);
  2926. String warningString = warning;
  2927. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2928. if (!AddErrorContext(warningString, refNode, isWhileSpecializing, true))
  2929. return NULL;
  2930. bool deferWarning = isWhileSpecializing != BfWhileSpecializingFlag_None;
  2931. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2932. {
  2933. // We used to bubble up warnings into the mixin injection site, BUT
  2934. // we are now assuming any relevant warnings will be given at the declaration site
  2935. return NULL;
  2936. }
  2937. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2938. {
  2939. BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Emitted code had errors", mCurMethodState->mEmitRefNode);
  2940. if (bfError != NULL)
  2941. mCompiler->mPassInstance->MoreInfo(warningString, refNode);
  2942. return bfError;
  2943. }
  2944. BfError* bfError;
  2945. if (refNode != NULL)
  2946. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warningString, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2947. else
  2948. bfError = mCompiler->mPassInstance->Warn(warningNum, warningString);
  2949. if (bfError != NULL)
  2950. {
  2951. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2952. bfError->mProject = mProject;
  2953. AddFailType(mCurTypeInstance);
  2954. mHadBuildWarning = true;
  2955. bfError->mIsPersistent = isPersistent;
  2956. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2957. {
  2958. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2959. if (parser != NULL)
  2960. {
  2961. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2962. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2963. if (warningNum != 0)
  2964. {
  2965. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  2966. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  2967. }
  2968. }
  2969. }
  2970. }
  2971. return bfError;
  2972. }
  2973. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfFieldInstance* fieldInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  2974. {
  2975. if (customAttributes == NULL)
  2976. return;
  2977. auto _AddDeclarationMoreInfo = [&]()
  2978. {
  2979. if (methodInstance != NULL)
  2980. {
  2981. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  2982. mCompiler->mPassInstance->MoreInfo(
  2983. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  2984. methodInstance->mMethodDef->GetRefNode());
  2985. }
  2986. else
  2987. {
  2988. mCompiler->mPassInstance->MoreInfo(
  2989. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  2990. typeInstance->mTypeDef->GetRefNode());
  2991. }
  2992. };
  2993. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  2994. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  2995. if ((customAttribute != NULL) && (targetSrc != NULL))
  2996. {
  2997. String err;
  2998. if (fieldInstance != NULL)
  2999. err = StrFormat("'%s' is obsolete", FieldToString(fieldInstance).c_str());
  3000. else if (methodInstance != NULL)
  3001. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  3002. else
  3003. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3004. bool isError = false;
  3005. if (customAttribute->mCtorArgs.size() >= 1)
  3006. {
  3007. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  3008. if (constant->mTypeCode == BfTypeCode_Boolean)
  3009. {
  3010. isError = constant->mBool;
  3011. }
  3012. else if (constant->mTypeCode == BfTypeCode_StringId)
  3013. {
  3014. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3015. if (str != NULL)
  3016. {
  3017. err += ":\n '";
  3018. err += *str;
  3019. err += "'";
  3020. }
  3021. if (customAttribute->mCtorArgs.size() >= 2)
  3022. {
  3023. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  3024. isError = constant->mBool;
  3025. }
  3026. }
  3027. }
  3028. BfError* error = NULL;
  3029. if (isError)
  3030. error = Fail(err, targetSrc);
  3031. else
  3032. error = Warn(0, err, targetSrc, false, true);
  3033. if (error != NULL)
  3034. _AddDeclarationMoreInfo();
  3035. }
  3036. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  3037. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3038. {
  3039. String err;
  3040. if (fieldInstance != NULL)
  3041. err += StrFormat("Method error: '", FieldToString(fieldInstance).c_str());
  3042. else if (methodInstance != NULL)
  3043. err += StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  3044. else
  3045. err += StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3046. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3047. if (str != NULL)
  3048. err += *str;
  3049. err += "'";
  3050. if (Fail(err, targetSrc) != NULL)
  3051. _AddDeclarationMoreInfo();
  3052. }
  3053. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  3054. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  3055. {
  3056. String err;
  3057. if (fieldInstance != NULL)
  3058. err += StrFormat("Field warning: '", FieldToString(fieldInstance).c_str());
  3059. else if (methodInstance != NULL)
  3060. err += StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  3061. else
  3062. err += StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3063. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3064. if (str != NULL)
  3065. err += *str;
  3066. err += "'";
  3067. if (Warn(0, err, targetSrc, false, true) != NULL)
  3068. _AddDeclarationMoreInfo();
  3069. }
  3070. }
  3071. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  3072. {
  3073. if (mBfIRBuilder->mOpFailed)
  3074. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  3075. }
  3076. void BfModule::FatalError(const StringImpl& error, const char* file, int line, int column)
  3077. {
  3078. static bool sHadFatalError = false;
  3079. static bool sHadReentrancy = false;
  3080. if (sHadFatalError)
  3081. {
  3082. return;
  3083. sHadReentrancy = true;
  3084. }
  3085. sHadFatalError = true;
  3086. String fullError = error;
  3087. if (file != NULL)
  3088. {
  3089. fullError += StrFormat(" at %s:%d", file, line);
  3090. if (column != -1)
  3091. fullError += StrFormat(":%d", column);
  3092. }
  3093. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3094. if (mCurTypeInstance != NULL)
  3095. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3096. if (mCurMethodInstance != NULL)
  3097. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3098. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3099. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3100. if (sHadReentrancy)
  3101. fullError += "\nError had reentrancy";
  3102. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  3103. }
  3104. void BfModule::FatalError(const StringImpl& error, BfAstNode* refNode)
  3105. {
  3106. if (refNode != NULL)
  3107. {
  3108. auto parser = refNode->GetParserData();
  3109. if (parser != NULL)
  3110. {
  3111. int line = -1;
  3112. int lineChar = -1;
  3113. parser->GetLineCharAtIdx(refNode->mSrcStart, line, lineChar);
  3114. if (line != -1)
  3115. FatalError(error, parser->mFileName.c_str(), line, lineChar);
  3116. }
  3117. }
  3118. FatalError(error);
  3119. }
  3120. void BfModule::InternalError(const StringImpl& error, BfAstNode* refNode, const char* file, int line)
  3121. {
  3122. String fullError = error;
  3123. if (file != NULL)
  3124. fullError += StrFormat(" at %s:%d", file, line);
  3125. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3126. if (mCurTypeInstance != NULL)
  3127. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3128. if (mCurMethodInstance != NULL)
  3129. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3130. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3131. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3132. Fail(String("INTERNAL ERROR: ") + fullError, refNode);
  3133. }
  3134. void BfModule::NotImpl(BfAstNode* astNode)
  3135. {
  3136. Fail("INTERNAL ERROR: Not implemented", astNode);
  3137. }
  3138. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  3139. {
  3140. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  3141. if (!allowPrivate)
  3142. allowPrivate |= memberType->IsInterface();
  3143. bool allowProtected = allowPrivate;
  3144. //TODO: We had this commented out, but this makes accessing protected properties fail
  3145. if (mCurTypeInstance != NULL)
  3146. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  3147. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  3148. {
  3149. return false;
  3150. }
  3151. return true;
  3152. }
  3153. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  3154. {
  3155. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  3156. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  3157. auto memberTypeInstance = memberType->ToTypeInstance();
  3158. if (memberTypeInstance == NULL)
  3159. {
  3160. auto underlyingType = memberType->GetUnderlyingType();
  3161. if (underlyingType != NULL)
  3162. return CheckDefineMemberProtection(protection, underlyingType);
  3163. return true;
  3164. }
  3165. if (memberTypeInstance->mTypeDef->mProtection < protection)
  3166. return false;
  3167. if (memberTypeInstance->IsGenericTypeInstance())
  3168. {
  3169. // When we're a generic struct, our data layout can depend on our generic parameters as well
  3170. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  3171. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3172. {
  3173. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  3174. return false;
  3175. }
  3176. }
  3177. return true;
  3178. }
  3179. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags, BfDepContext* depContext)
  3180. {
  3181. if (usedType == userType)
  3182. return;
  3183. if (((flags & BfDependencyMap::DependencyFlag_ConstValue) != 0) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_FieldType))
  3184. {
  3185. // This can be an `int32[UsedType.cVal]` type reference
  3186. flags = (BfDependencyMap::DependencyFlags)(flags | BfDependencyMap::DependencyFlag_ValueTypeSizeDep);
  3187. }
  3188. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  3189. {
  3190. if (userType->IsMethodRef())
  3191. {
  3192. // We cannot short-circuit dependencies because of method group ref counting
  3193. }
  3194. else
  3195. return;
  3196. }
  3197. if (usedType->IsSpecializedByAutoCompleteMethod())
  3198. {
  3199. if ((flags & (BfDependencyMap::DependencyFlag_TypeGenericArg | BfDependencyMap::DependencyFlag_MethodGenericArg |
  3200. BfDependencyMap::DependencyFlag_OuterType | BfDependencyMap::DependencyFlag_DerivedFrom)) == 0)
  3201. return;
  3202. }
  3203. // if (usedType->IsBoxed())
  3204. // {
  3205. // NOP;
  3206. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  3207. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  3208. // {
  3209. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  3210. // }
  3211. // }
  3212. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  3213. // BfType* origUsedType = usedType;
  3214. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  3215. // if (isDataAccess)
  3216. // {
  3217. // while (true)
  3218. // {
  3219. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  3220. // usedType = usedType->GetUnderlyingType();
  3221. // else if (usedType->IsArray())
  3222. // {
  3223. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  3224. // }
  3225. // else
  3226. // break;
  3227. // }
  3228. // }
  3229. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  3230. {
  3231. bool addType = true;
  3232. auto checkType = usedType;
  3233. PopulateType(checkType, BfPopulateType_Data);
  3234. if (checkType->IsValuelessType())
  3235. addType = false;
  3236. else if (checkType->IsPrimitiveType())
  3237. addType = false;
  3238. else
  3239. {
  3240. auto checkTypeInst = checkType->ToTypeInstance();
  3241. if (checkTypeInst == NULL)
  3242. {
  3243. addType = false;
  3244. }
  3245. else
  3246. {
  3247. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  3248. addType = false;
  3249. }
  3250. }
  3251. if (addType)
  3252. {
  3253. auto checkTypeInst = checkType->ToTypeInstance();
  3254. if (checkTypeInst->mHotTypeData != NULL)
  3255. {
  3256. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  3257. BF_ASSERT(hotTypeVersion != NULL);
  3258. if (hotTypeVersion != NULL)
  3259. {
  3260. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  3261. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  3262. (checkType->IsComposite()))
  3263. isAllocation = true;
  3264. if (isAllocation)
  3265. {
  3266. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  3267. }
  3268. else
  3269. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  3270. }
  3271. }
  3272. }
  3273. }
  3274. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  3275. {
  3276. auto usingModule = userType->GetModule();
  3277. BfModule* usedModule;
  3278. if (usedType->IsFunction())
  3279. {
  3280. if (mCompiler->mFunctionTypeDef != NULL)
  3281. {
  3282. auto functionType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  3283. usedModule = functionType->GetModule();
  3284. }
  3285. }
  3286. else
  3287. usedModule = usedType->GetModule();
  3288. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  3289. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  3290. {
  3291. if ((flags & ~(BfDependencyMap::DependencyFlag_OuterType)) == 0)
  3292. {
  3293. // Not a 'use' dependency
  3294. }
  3295. else
  3296. {
  3297. usingModule->mModuleRefs.Add(usedModule);
  3298. }
  3299. }
  3300. }
  3301. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  3302. {
  3303. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  3304. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  3305. if (genericArg == usedType)
  3306. return;
  3307. }
  3308. auto depFlag = flags;
  3309. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  3310. {
  3311. if (usedType->IsDependendType())
  3312. {
  3313. // Cause a rebuild but not an outright deletion of the type
  3314. // We can only do this if the 'usedType' can actually hold the dependency which can actually trigger a deletion chain
  3315. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef;
  3316. }
  3317. }
  3318. if (usedType->IsTypeAlias())
  3319. {
  3320. auto underlyingType = usedType->GetUnderlyingType();
  3321. if (underlyingType != NULL)
  3322. {
  3323. BfDepContext newDepContext;
  3324. if (depContext == NULL)
  3325. depContext = &newDepContext;
  3326. if (++depContext->mAliasDepth > 8)
  3327. {
  3328. if (!depContext->mDeepSeenAliases.Add(underlyingType))
  3329. return; // Circular!
  3330. }
  3331. AddDependency(underlyingType, userType, depFlag);
  3332. }
  3333. }
  3334. else if (!usedType->IsGenericTypeInstance())
  3335. {
  3336. auto underlyingType = usedType->GetUnderlyingType();
  3337. if (underlyingType != NULL)
  3338. AddDependency(underlyingType, userType, depFlag);
  3339. }
  3340. BfDependedType* checkDType = usedType->ToDependedType();
  3341. if (checkDType == NULL)
  3342. return;
  3343. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  3344. mContext->MarkAsReferenced(checkDType);
  3345. #ifdef _DEBUG
  3346. // If a MethodRef depends ON US, that means it's a local method that we own
  3347. if (userType->IsMethodRef())
  3348. {
  3349. auto methodRefType = (BfMethodRefType*)userType;
  3350. BF_ASSERT(methodRefType->mOwner == checkDType);
  3351. }
  3352. #endif
  3353. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  3354. return;
  3355. if ((checkDType->IsGenericTypeInstance()) && (!userType->IsMethodRef()))
  3356. {
  3357. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  3358. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3359. {
  3360. AddDependency(genericArg, userType, depFlag);
  3361. }
  3362. }
  3363. if (checkDType->IsTuple())
  3364. {
  3365. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  3366. {
  3367. if (field.mDataIdx != -1)
  3368. AddDependency(field.mResolvedType, userType, depFlag);
  3369. }
  3370. }
  3371. }
  3372. void BfModule::AddDependency(BfGenericParamInstance* genericParam, BfTypeInstance* usingType)
  3373. {
  3374. if ((genericParam->mExternType != NULL) && (!genericParam->mExternType->IsGenericParam()))
  3375. AddDependency(genericParam->mExternType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3376. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  3377. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3378. for (auto& operatorConstraint : genericParam->mOperatorConstraints)
  3379. {
  3380. if (operatorConstraint.mLeftType != NULL)
  3381. AddDependency(operatorConstraint.mLeftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3382. if (operatorConstraint.mRightType != NULL)
  3383. AddDependency(operatorConstraint.mRightType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3384. }
  3385. if (genericParam->mTypeConstraint != NULL)
  3386. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3387. }
  3388. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  3389. {
  3390. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  3391. {
  3392. if (methodInstance->mHotMethod == NULL)
  3393. CheckHotMethod(methodInstance, "");
  3394. BF_ASSERT(methodInstance->mHotMethod != NULL);
  3395. if (devirtualized)
  3396. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  3397. else
  3398. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  3399. }
  3400. }
  3401. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  3402. {
  3403. auto checkTypeInst = typeInst;
  3404. while (checkTypeInst != NULL)
  3405. {
  3406. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  3407. return true;
  3408. checkTypeInst = checkTypeInst->mBaseType;
  3409. }
  3410. return false;
  3411. }
  3412. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  3413. {
  3414. if (mContext->mCurTypeState == NULL)
  3415. return;
  3416. BP_ZONE("PopulateGlobalContainersList");
  3417. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  3418. if ((userTypeDef == NULL) && (mCurMethodInstance != NULL))
  3419. userTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  3420. if (userTypeDef == NULL)
  3421. userTypeDef = mCurTypeInstance->mTypeDef;
  3422. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  3423. {
  3424. mContext->mCurTypeState->mGlobalContainers.Clear();
  3425. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  3426. {
  3427. BfAtomComposite findStr;
  3428. if (namespaceIdx != -1)
  3429. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  3430. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  3431. while (typeDefItr)
  3432. {
  3433. auto typeDef = *typeDefItr;
  3434. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  3435. {
  3436. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  3437. {
  3438. BfGlobalContainerEntry globalEntry;
  3439. globalEntry.mTypeDef = typeDef;
  3440. globalEntry.mTypeInst = NULL;
  3441. typeDef->PopulateMemberSets();
  3442. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  3443. }
  3444. }
  3445. else if (!typeDef->mIsPartial)
  3446. {
  3447. //break;
  3448. }
  3449. typeDefItr.MoveToNextHashMatch();
  3450. }
  3451. }
  3452. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  3453. }
  3454. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  3455. // reifing types
  3456. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  3457. {
  3458. if (globalEntry.mTypeInst == NULL)
  3459. {
  3460. bool include = false;
  3461. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  3462. include = true;
  3463. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  3464. {
  3465. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  3466. include = true;
  3467. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  3468. include = true;
  3469. }
  3470. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  3471. {
  3472. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  3473. include = true;
  3474. }
  3475. if (include)
  3476. {
  3477. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  3478. if (type != NULL)
  3479. globalEntry.mTypeInst = type->ToTypeInstance();
  3480. }
  3481. }
  3482. }
  3483. }
  3484. BfStaticSearch* BfModule::GetStaticSearch()
  3485. {
  3486. auto activeTypeDef = GetActiveTypeDef();
  3487. BfStaticSearch* staticSearch = NULL;
  3488. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3489. return staticSearch;
  3490. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3491. return staticSearch;
  3492. return NULL;
  3493. }
  3494. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  3495. {
  3496. auto activeTypeDef = GetActiveTypeDef();
  3497. BfInternalAccessSet* internalAccessSet = NULL;
  3498. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3499. return internalAccessSet;
  3500. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3501. return internalAccessSet;
  3502. return NULL;
  3503. }
  3504. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  3505. {
  3506. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  3507. return true;
  3508. if ((mCurMethodInstance != NULL) &&
  3509. ((mCurMethodInstance->mIsUnspecializedVariation) || (mCurMethodInstance->IsSpecializedGenericMethod())))
  3510. return true;
  3511. auto internalAccessSet = GetInternalAccessSet();
  3512. if (internalAccessSet == NULL)
  3513. return false;
  3514. for (auto& nameComposite : internalAccessSet->mNamespaces)
  3515. {
  3516. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  3517. return true;
  3518. }
  3519. for (auto internalType : internalAccessSet->mTypes)
  3520. {
  3521. auto checkTypeDef = usingTypeDef->GetDefinition();
  3522. while (checkTypeDef != NULL)
  3523. {
  3524. if (checkTypeDef == internalType->mTypeDef->GetDefinition())
  3525. return true;
  3526. checkTypeDef = checkTypeDef->mOuterType;
  3527. }
  3528. }
  3529. return false;
  3530. }
  3531. void PrintUsers(llvm::MDNode* md);
  3532. BfModuleOptions BfModule::GetModuleOptions()
  3533. {
  3534. if (mIsScratchModule)
  3535. return BfModuleOptions();
  3536. if (mModuleOptions != NULL)
  3537. return *mModuleOptions;
  3538. BfModuleOptions moduleOptions;
  3539. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3540. if (mProject != NULL)
  3541. {
  3542. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3543. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3544. }
  3545. auto headModule = this;
  3546. while (headModule->mParentModule != NULL)
  3547. headModule = headModule->mParentModule;
  3548. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata") || mIsSpecialModule);
  3549. if (headModule->mOwnedTypeInstances.size() > 0)
  3550. {
  3551. auto typeInst = headModule->mOwnedTypeInstances[0];
  3552. if (typeInst->mTypeOptionsIdx == -2)
  3553. PopulateType(typeInst);
  3554. if (typeInst->mTypeOptionsIdx != -1)
  3555. {
  3556. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3557. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3558. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3559. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3560. }
  3561. }
  3562. return moduleOptions;
  3563. }
  3564. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3565. {
  3566. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3567. return BfCheckedKind_Unchecked;
  3568. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3569. auto typeOptions = GetTypeOptions();
  3570. if (typeOptions != NULL)
  3571. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3572. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3573. }
  3574. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3575. {
  3576. BF_ASSERT(typeInstance != NULL);
  3577. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_InFailTypes) != 0)
  3578. return;
  3579. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_InFailTypes);
  3580. mContext->mFailTypes.TryAdd(typeInstance, BfFailKind_Normal);
  3581. }
  3582. void BfModule::DeferRebuildType(BfTypeInstance* typeInstance)
  3583. {
  3584. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_RebuildQueued) != 0)
  3585. return;
  3586. mCompiler->mHasQueuedTypeRebuilds = true;
  3587. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_RebuildQueued);
  3588. AddFailType(typeInstance);
  3589. }
  3590. void BfModule::CheckAddFailType()
  3591. {
  3592. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3593. // but we still need to add the owning type to the FailTypes list
  3594. //.. OLD:
  3595. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3596. /*if (mCurTypeInstance->mModule != this)
  3597. return;*/
  3598. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3599. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3600. // being recompiled. This forces types with warnings to be recompiled.
  3601. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3602. // constantly warning-aware
  3603. if ((mHadBuildError) ||
  3604. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3605. {
  3606. //mContext->mFailTypes.Add(mCurTypeInstance);
  3607. }
  3608. }
  3609. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3610. {
  3611. if (!mCompiler->IsHotCompile())
  3612. return;
  3613. typeInst->mDirty = true;
  3614. for (auto& dep : typeInst->mDependencyMap)
  3615. {
  3616. auto depType = dep.mKey;
  3617. auto depFlags = dep.mValue.mFlags;
  3618. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3619. {
  3620. MarkDerivedDirty(depType->ToTypeInstance());
  3621. }
  3622. }
  3623. }
  3624. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3625. {
  3626. auto fieldType = fieldInstance->GetResolvedType();
  3627. auto field = fieldInstance->GetFieldDef();
  3628. if (fieldType->IsVar())
  3629. return;
  3630. BfIRValue initValue;
  3631. if (field->mIsConst)
  3632. {
  3633. if (fieldType->IsPointer())
  3634. fieldType = fieldType->GetUnderlyingType();
  3635. }
  3636. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3637. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3638. storageKind = BfIRStorageKind_Export;
  3639. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3640. storageKind = BfIRStorageKind_Import;
  3641. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3642. initValue = GetDefaultValue(fieldType);
  3643. if (fieldInstance->mOwner->IsUnspecializedType())
  3644. {
  3645. // Placeholder
  3646. auto ptrVal = CreatePointerType(fieldType);
  3647. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3648. }
  3649. else
  3650. {
  3651. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3652. StringT<4096> staticVarName;
  3653. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3654. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3655. {
  3656. BfIRType irType;
  3657. if (fieldInstance->IsAppendedObject())
  3658. {
  3659. irType = mBfIRBuilder->MapTypeInst(fieldType->ToTypeInstance(), BfIRPopulateType_Eventually_Full);
  3660. initValue = mBfIRBuilder->CreateConstAggZero(irType);
  3661. }
  3662. else
  3663. irType = mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full);
  3664. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3665. irType,
  3666. false,
  3667. BfIRLinkageType_External,
  3668. initValue,
  3669. staticVarName,
  3670. isThreadLocal);
  3671. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3672. if (storageKind != BfIRStorageKind_Normal)
  3673. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3674. BF_ASSERT(globalVar);
  3675. mStaticFieldRefs[fieldInstance] = globalVar;
  3676. }
  3677. }
  3678. }
  3679. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3680. {
  3681. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3682. BfType* fieldType = NULL;
  3683. if (fieldInstance != NULL)
  3684. {
  3685. fieldType = fieldInstance->GetResolvedType();
  3686. if (fieldType == NULL)
  3687. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3688. }
  3689. else
  3690. {
  3691. BF_ASSERT(mCompiler->IsAutocomplete());
  3692. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3693. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3694. {
  3695. fieldType = typeInstance;
  3696. }
  3697. else
  3698. {
  3699. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3700. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3701. if (isLet || isVar)
  3702. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3703. else
  3704. fieldType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  3705. if (fieldType == NULL)
  3706. fieldType = mContext->mBfObjectType;
  3707. }
  3708. }
  3709. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3710. return;
  3711. if (mContext->mFieldResolveReentrys.size() > 1)
  3712. {
  3713. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3714. {
  3715. String failStr = "Circular data reference detected between the following fields:";
  3716. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3717. {
  3718. if (i > 1)
  3719. failStr += ",";
  3720. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3721. }
  3722. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3723. if (err)
  3724. err->mIsPersistent = true;
  3725. return;
  3726. }
  3727. }
  3728. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3729. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3730. if (fieldInstance == NULL)
  3731. popTypeResolveReentry.Pop();
  3732. auto typeDef = typeInstance->mTypeDef;
  3733. BfIRValue constValue;
  3734. if (fieldDef->mIsExtern)
  3735. {
  3736. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3737. {
  3738. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3739. Fail("Extern consts must be pointer types", fieldDef->mTypeRef);
  3740. }
  3741. if (fieldDef->GetInitializer() != NULL)
  3742. {
  3743. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3744. Fail("Extern consts cannot have initializers", fieldDef->GetNameNode());
  3745. }
  3746. }
  3747. else if (fieldDef->GetInitializer() == NULL)
  3748. {
  3749. if (fieldDef->IsEnumCaseEntry())
  3750. {
  3751. if (typeInstance->IsTypedPrimitive())
  3752. {
  3753. BfFieldInstance* prevFieldInstance = NULL;
  3754. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3755. {
  3756. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3757. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3758. {
  3759. prevFieldInstance = checkFieldInst;
  3760. break;
  3761. }
  3762. }
  3763. if (prevFieldInstance == NULL)
  3764. constValue = GetConstValue(0, typeInstance);
  3765. else
  3766. {
  3767. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3768. if (prevFieldInstance->mConstIdx == -1)
  3769. {
  3770. if (!mCompiler->IsAutocomplete())
  3771. AssertErrorState();
  3772. constValue = GetConstValue(0, typeInstance);
  3773. }
  3774. else
  3775. {
  3776. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3777. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3778. }
  3779. }
  3780. }
  3781. }
  3782. else
  3783. {
  3784. Fail("Const requires initializer", fieldDef->GetNameNode());
  3785. }
  3786. }
  3787. else if (mBfIRBuilder != NULL)
  3788. {
  3789. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3790. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3791. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3792. BfMethodState methodState;
  3793. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3794. methodState.mTempKind = BfMethodState::TempKind_Static;
  3795. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3796. if ((fieldType->IsVar()) || (fieldType->IsUndefSizedArray()))
  3797. {
  3798. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3799. if (!initValue)
  3800. {
  3801. AssertErrorState();
  3802. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3803. }
  3804. if (fieldInstance != NULL)
  3805. {
  3806. if (fieldType->IsUndefSizedArray())
  3807. {
  3808. if ((initValue.mType->IsSizedArray()) && (initValue.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3809. {
  3810. fieldInstance->mResolvedType = initValue.mType;
  3811. }
  3812. }
  3813. else
  3814. fieldInstance->mResolvedType = initValue.mType;
  3815. }
  3816. constValue = initValue.mValue;
  3817. }
  3818. else
  3819. {
  3820. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3821. constValue = uncastedInitValue.mValue;
  3822. }
  3823. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3824. {
  3825. // Illegal
  3826. constValue = BfIRValue();
  3827. }
  3828. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3829. }
  3830. if (fieldInstance != NULL)
  3831. {
  3832. fieldType = fieldInstance->GetResolvedType();
  3833. if ((fieldType == NULL) || (fieldType->IsVar()))
  3834. {
  3835. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3836. AssertErrorState();
  3837. // Default const type is 'int'
  3838. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3839. if (fieldInstance != NULL)
  3840. {
  3841. fieldInstance->mResolvedType = initValue.mType;
  3842. }
  3843. constValue = initValue.mValue;
  3844. }
  3845. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3846. {
  3847. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3848. CurrentAddToConstHolder(constValue);
  3849. fieldInstance->mConstIdx = constValue.mId;
  3850. }
  3851. }
  3852. }
  3853. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3854. {
  3855. bool isDeclType = (field->mFieldDeclaration != NULL) && BfNodeDynCastExact<BfExprModTypeRef>(field->mTypeRef) != NULL;
  3856. auto fieldType = fieldInstance->GetResolvedType();
  3857. if ((field->mIsConst) && (!isDeclType))
  3858. {
  3859. ResolveConstField(typeInstance, fieldInstance, field);
  3860. return fieldInstance->GetResolvedType();
  3861. }
  3862. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3863. if (!fieldInstance->mIsInferredType)
  3864. return fieldType;
  3865. if ((!fieldType->IsVar()) && (!fieldType->IsUndefSizedArray()))
  3866. return fieldType;
  3867. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3868. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3869. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mType != typeInstance);
  3870. auto typeDef = typeInstance->mTypeDef;
  3871. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3872. {
  3873. AssertErrorState();
  3874. return fieldType;
  3875. }
  3876. bool hadInferenceCycle = false;
  3877. if (mContext->mFieldResolveReentrys.size() > 1)
  3878. {
  3879. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3880. {
  3881. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3882. {
  3883. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3884. auto fieldDef = fieldInst->GetFieldDef();
  3885. auto fieldOwner = fieldInst->mOwner;
  3886. auto fieldModule = fieldOwner->mModule;
  3887. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3888. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3889. }
  3890. return fieldType;
  3891. }
  3892. }
  3893. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3894. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3895. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3896. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3897. if ((field->GetInitializer() == NULL) && (!isDeclType))
  3898. {
  3899. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3900. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3901. return fieldType;
  3902. }
  3903. BfType* resolvedType = NULL;
  3904. if (!hadInferenceCycle)
  3905. {
  3906. BfTypeState typeState;
  3907. typeState.mPrevState = mContext->mCurTypeState;
  3908. typeState.mType = typeInstance;
  3909. typeState.mCurFieldDef = field;
  3910. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3911. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3912. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3913. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3914. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3915. BfMethodState methodState;
  3916. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3917. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3918. if (!staticOnly)
  3919. {
  3920. //BfLocalVariable localVar;
  3921. //methodState.mLocals.push_back(localVar);
  3922. }
  3923. if (isDeclType)
  3924. {
  3925. auto fieldDef = fieldInstance->GetFieldDef();
  3926. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3927. }
  3928. else
  3929. {
  3930. BfTypedValue valueFromExpr;
  3931. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3932. FixIntUnknown(valueFromExpr);
  3933. if (fieldType->IsUndefSizedArray())
  3934. {
  3935. if ((valueFromExpr.mType != NULL) && (valueFromExpr.mType->IsSizedArray()) && (valueFromExpr.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3936. resolvedType = valueFromExpr.mType;
  3937. }
  3938. else
  3939. resolvedType = valueFromExpr.mType;
  3940. }
  3941. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3942. }
  3943. if (resolvedType == NULL)
  3944. return fieldType;
  3945. fieldInstance->SetResolvedType(resolvedType);
  3946. if (field->mIsStatic)
  3947. {
  3948. }
  3949. else if (fieldInstance->mDataIdx >= 0)
  3950. {
  3951. }
  3952. else
  3953. {
  3954. BF_ASSERT(typeInstance->IsIncomplete());
  3955. }
  3956. return resolvedType;
  3957. }
  3958. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3959. {
  3960. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3961. auto fieldType = fieldInstance->GetResolvedType();
  3962. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3963. {
  3964. int fieldIdx = 0;
  3965. int fieldCount = 0;
  3966. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  3967. fieldIdx--;
  3968. int count = fieldCount;
  3969. if (fieldIdx == -1)
  3970. count = 1;
  3971. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3972. auto thisVariable = GetThisVariable();
  3973. if (thisVariable != NULL)
  3974. {
  3975. for (int i = 0; i < count; i++)
  3976. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  3977. }
  3978. }
  3979. }
  3980. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3981. {
  3982. if (fieldInstance->mCustomAttributes == NULL)
  3983. return false;
  3984. auto fieldDef = fieldInstance->GetFieldDef();
  3985. if (!fieldDef->mIsStatic)
  3986. return false;
  3987. bool isThreadLocal = false;
  3988. if (fieldInstance->mCustomAttributes != NULL)
  3989. {
  3990. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3991. {
  3992. if (customAttr.mType->ToTypeInstance()->IsInstanceOf(mCompiler->mThreadStaticAttributeTypeDef))
  3993. return true;
  3994. }
  3995. }
  3996. return false;
  3997. }
  3998. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  3999. {
  4000. if (fieldDef == NULL)
  4001. fieldDef = fieldInstance->GetFieldDef();
  4002. if (fieldType == NULL)
  4003. fieldType = fieldInstance->GetResolvedType();
  4004. if (initializer == NULL)
  4005. {
  4006. if (fieldDef == NULL)
  4007. return BfTypedValue();
  4008. initializer = fieldDef->GetInitializer();
  4009. }
  4010. BfTypedValue staticVarRef;
  4011. BfTypedValue result;
  4012. if (initializer == NULL)
  4013. {
  4014. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  4015. }
  4016. else
  4017. {
  4018. if (mCompiler->mIsResolveOnly)
  4019. {
  4020. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  4021. {
  4022. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  4023. sourceClassifier->VisitChildNoRef(initializer);
  4024. }
  4025. }
  4026. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  4027. {
  4028. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  4029. BfConstResolver constResolver(this);
  4030. constResolver.Resolve(initializer);
  4031. return GetDefaultTypedValue(fieldType);
  4032. }
  4033. else if (mCurTypeInstance->IsUnspecializedTypeVariation())
  4034. {
  4035. return GetDefaultTypedValue(fieldType);
  4036. }
  4037. else if (fieldDef->mIsConst)
  4038. {
  4039. int ceExecuteId = -1;
  4040. if (mCompiler->mCeMachine != NULL)
  4041. ceExecuteId = mCompiler->mCeMachine->mExecuteId;
  4042. BfTypeState typeState;
  4043. typeState.mType = mCurTypeInstance;
  4044. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  4045. typeState.mCurFieldDef = fieldDef;
  4046. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  4047. BfConstResolver constResolver(this);
  4048. if (fieldType->IsVar())
  4049. return constResolver.Resolve(initializer);
  4050. else
  4051. {
  4052. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  4053. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  4054. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  4055. {
  4056. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  4057. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  4058. resolveFlags = BfConstResolveFlag_NoCast;
  4059. }
  4060. UpdateSrcPos(initializer);
  4061. auto result = constResolver.Resolve(initializer, fieldType, resolveFlags);
  4062. if ((mCompiler->mCeMachine != NULL) && (fieldInstance != NULL))
  4063. {
  4064. if (mCompiler->mCeMachine->mExecuteId != ceExecuteId)
  4065. fieldInstance->mHadConstEval = true;
  4066. }
  4067. if (auto autoComplete = mCompiler->GetAutoComplete())
  4068. autoComplete->CheckResult(initializer, result);
  4069. return result;
  4070. }
  4071. }
  4072. BfExprEvaluator exprEvaluator(this);
  4073. if (doStore)
  4074. {
  4075. staticVarRef = ReferenceStaticField(fieldInstance);
  4076. exprEvaluator.mReceivingValue = &staticVarRef;
  4077. }
  4078. if (fieldType->IsVar())
  4079. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4080. else
  4081. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4082. if (doStore)
  4083. {
  4084. if (exprEvaluator.mReceivingValue == NULL)
  4085. doStore = false; // Already stored
  4086. }
  4087. }
  4088. if (fieldInstance != NULL)
  4089. MarkFieldInitialized(fieldInstance);
  4090. if ((doStore) && (result))
  4091. {
  4092. if (fieldInstance->mResolvedType->IsUndefSizedArray())
  4093. {
  4094. if ((!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mFastFinish))
  4095. AssertErrorState();
  4096. }
  4097. else
  4098. {
  4099. result = LoadValue(result);
  4100. if (!result.mType->IsValuelessType())
  4101. mBfIRBuilder->CreateAlignedStore(result.mValue, staticVarRef.mValue, result.mType->mAlign);
  4102. }
  4103. }
  4104. return result;
  4105. }
  4106. void BfModule::AppendedObjectInit(BfFieldInstance* fieldInst)
  4107. {
  4108. BfExprEvaluator exprEvaluator(this);
  4109. bool failed = false;
  4110. auto fieldDef = fieldInst->GetFieldDef();
  4111. auto initializer = fieldDef->GetInitializer();
  4112. BfResolvedArgs resolvedArgs;
  4113. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(initializer))
  4114. {
  4115. bool isDot = false;
  4116. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  4117. isDot = (memberRefExpr->mTarget == NULL) && (memberRefExpr->mMemberName == NULL);
  4118. if (!isDot)
  4119. {
  4120. auto resolvedType = ResolveTypeRef(invocationExpr->mTarget, {});
  4121. if ((resolvedType == NULL) || (resolvedType != fieldInst->mResolvedType))
  4122. failed = true;
  4123. }
  4124. SetAndRestoreValue<BfType*> prevExpectingType(exprEvaluator.mExpectingType, fieldInst->mResolvedType);
  4125. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  4126. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  4127. }
  4128. else if (initializer != NULL)
  4129. {
  4130. GetFieldInitializerValue(fieldInst);
  4131. failed = true;
  4132. }
  4133. if (failed)
  4134. Fail("Append fields can only be initialized with a call to their constructor", initializer);
  4135. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  4136. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4137. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4138. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  4139. auto fieldTypeInst = fieldInst->mResolvedType->ToTypeInstance();
  4140. BfIRValue fieldAddr;
  4141. if (fieldDef->mIsStatic)
  4142. {
  4143. fieldAddr = ReferenceStaticField(fieldInst).mValue;
  4144. }
  4145. else
  4146. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  4147. auto thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  4148. auto indexVal = BfTypedValue(CreateAlloca(intType), CreateRefType(intType));
  4149. auto intThisVal = mBfIRBuilder->CreatePtrToInt(thisValue.mValue, (intType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  4150. auto curValPtr = mBfIRBuilder->CreateAdd(intThisVal, GetConstValue(fieldTypeInst->mInstSize, intType));
  4151. mBfIRBuilder->CreateStore(curValPtr, indexVal.mValue);
  4152. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 0);
  4153. auto vDataRef = CreateClassVDataGlobal(fieldInst->mResolvedType->ToTypeInstance());
  4154. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  4155. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  4156. mBfIRBuilder->CreateStore(srcVal, destAddr);
  4157. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  4158. {
  4159. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4160. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4161. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(thisValue.mValue, ptrType);
  4162. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_AppendAlloc), thisFlagsPtr);
  4163. }
  4164. exprEvaluator.MatchConstructor(fieldDef->GetNameNode(), NULL, thisValue, fieldInst->mResolvedType->ToTypeInstance(), resolvedArgs, false, BfMethodGenericArguments(), true, &indexVal);
  4165. }
  4166. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  4167. {
  4168. }
  4169. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  4170. {
  4171. PopulateType(classType);
  4172. if (isInterfacePass)
  4173. {
  4174. for (auto ifaceInst : classType->mInterfaces)
  4175. {
  4176. if (exChecks->Contains(ifaceInst.mInterfaceType))
  4177. continue;
  4178. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  4179. continue;
  4180. if (ifaceInst.mDeclaringType->IsExtension())
  4181. {
  4182. bool needsExCheck = false;
  4183. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  4184. {
  4185. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  4186. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  4187. {
  4188. exChecks->push_back(ifaceInst.mInterfaceType);
  4189. continue;
  4190. }
  4191. else
  4192. {
  4193. // We can only do an 'exCheck' if we're actually going to slot this interface
  4194. }
  4195. }
  4196. }
  4197. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  4198. }
  4199. }
  4200. else
  4201. {
  4202. outVals->push_back(classType->mTypeId);
  4203. }
  4204. if (classType->mBaseType != NULL)
  4205. {
  4206. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  4207. }
  4208. }
  4209. void BfModule::CreateDynamicCastMethod()
  4210. {
  4211. auto objType = mContext->mBfObjectType;
  4212. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  4213. {
  4214. // The main reason to punt on this method for ResolveOnly is because types can be created
  4215. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  4216. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  4217. // remove this punt when we recycle typeId's
  4218. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  4219. mCurMethodState->mHadReturn = true;
  4220. return;
  4221. }
  4222. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  4223. auto func = mCurMethodState->mIRFunction;
  4224. auto thisValue = mBfIRBuilder->GetArgument(0);
  4225. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  4226. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4227. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  4228. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  4229. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  4230. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  4231. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  4232. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4233. SizedArray<int, 8> typeMatches;
  4234. SizedArray<BfTypeInstance*, 8> exChecks;
  4235. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  4236. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  4237. {
  4238. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  4239. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  4240. BfTypeVector genericArgs;
  4241. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  4242. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  4243. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef->GetDefinition(), genericArgs, BfPopulateType_Declaration);
  4244. typeMatches.push_back(unboundType->mTypeId);
  4245. }
  4246. if (mCurTypeInstance->IsBoxed())
  4247. {
  4248. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  4249. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  4250. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  4251. if (innerType->IsTypedPrimitive())
  4252. {
  4253. auto underlyingType = innerType->GetUnderlyingType();
  4254. typeMatches.push_back(underlyingType->mTypeId);
  4255. }
  4256. auto innerTypeInst = innerType->ToTypeInstance();
  4257. if ((innerTypeInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef)) ||
  4258. (innerTypeInst->IsInstanceOf(mCompiler->mPointerTTypeDef)) ||
  4259. (innerTypeInst->IsInstanceOf(mCompiler->mMethodRefTypeDef)))
  4260. {
  4261. PopulateType(innerTypeInst);
  4262. //TODO: What case was this supposed to handle?
  4263. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  4264. }
  4265. }
  4266. auto curBlock = mBfIRBuilder->GetInsertBlock();
  4267. BfIRValue vDataPtr;
  4268. if (!exChecks.empty())
  4269. {
  4270. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4271. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  4272. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  4273. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4274. }
  4275. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  4276. for (auto typeMatch : typeMatches)
  4277. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  4278. Array<BfIRValue> incomingFalses;
  4279. for (auto ifaceTypeInst : exChecks)
  4280. {
  4281. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  4282. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  4283. mBfIRBuilder->SetInsertPoint(nextBB);
  4284. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  4285. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4286. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4287. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4288. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  4289. incomingFalses.push_back(nextBB);
  4290. }
  4291. mBfIRBuilder->AddBlock(trueBB);
  4292. mBfIRBuilder->SetInsertPoint(trueBB);
  4293. mBfIRBuilder->CreateBr(exitBB);
  4294. mBfIRBuilder->AddBlock(exitBB);
  4295. mBfIRBuilder->SetInsertPoint(exitBB);
  4296. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  4297. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  4298. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  4299. for (auto incomingFalseBlock : incomingFalses)
  4300. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  4301. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  4302. mBfIRBuilder->CreateRet(phi);
  4303. mCurMethodState->mHadReturn = true;
  4304. }
  4305. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  4306. {
  4307. BfExprEvaluator exprEvaluator(this);
  4308. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  4309. auto typeInst = rightValue.mType->ToTypeInstance();
  4310. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  4311. BfTypedValue result = exprEvaluator.GetResult();
  4312. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  4313. {
  4314. // Fail?
  4315. }
  4316. if ((result) && (!result.mType->IsVar()))
  4317. {
  4318. auto nextBB = mBfIRBuilder->CreateBlock("next");
  4319. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  4320. mBfIRBuilder->AddBlock(nextBB);
  4321. mBfIRBuilder->SetInsertPoint(nextBB);
  4322. }
  4323. }
  4324. void BfModule::CreateFakeCallerMethod(const String& funcName)
  4325. {
  4326. if (mCurMethodInstance->mHasFailed)
  4327. return;
  4328. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  4329. return;
  4330. BF_ASSERT(mCurMethodInstance->mIRFunction);
  4331. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  4332. SizedArray<BfIRType, 4> paramTypes;
  4333. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  4334. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  4335. mBfIRBuilder->SetActiveFunction(func);
  4336. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  4337. mBfIRBuilder->SetInsertPoint(entryBlock);
  4338. BfMethodState methodState;
  4339. methodState.mIRHeadBlock = entryBlock;
  4340. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4341. SizedArray<BfIRValue, 8> args;
  4342. BfExprEvaluator exprEvaluator(this);
  4343. if (mCurMethodInstance->GetStructRetIdx() == 0)
  4344. {
  4345. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4346. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4347. }
  4348. if (mCurMethodInstance->HasThis())
  4349. {
  4350. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  4351. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  4352. }
  4353. if (mCurMethodInstance->GetStructRetIdx() == 1)
  4354. {
  4355. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4356. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4357. }
  4358. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  4359. {
  4360. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  4361. if (paramType->IsValuelessType())
  4362. continue;
  4363. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  4364. }
  4365. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  4366. mBfIRBuilder->CreateRetVoid();
  4367. }
  4368. void BfModule::CreateDelegateEqualsMethod()
  4369. {
  4370. if (mBfIRBuilder->mIgnoreWrites)
  4371. return;
  4372. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4373. if (refNode == NULL)
  4374. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4375. UpdateSrcPos(refNode);
  4376. SetIllegalSrcPos();
  4377. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4378. auto resultVal = CreateAlloca(boolType);
  4379. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4380. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4381. auto delegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  4382. mBfIRBuilder->PopulateType(delegateType);
  4383. BfExprEvaluator exprEvaluator(this);
  4384. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4385. BfTypedValue lhsDelegate = BfTypedValue(mBfIRBuilder->CreateBitCast(leftTypedVal.mValue, mBfIRBuilder->MapType(delegateType)), delegateType);
  4386. BfTypedValue rhsDelegate = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4387. rhsDelegate = LoadValue(rhsDelegate);
  4388. BfTypedValue rightTypedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(rhsDelegate.mValue, mBfIRBuilder->MapType(mCurTypeInstance)), mCurTypeInstance);
  4389. auto& targetFieldInstance = delegateType->mFieldInstances[0];
  4390. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(lhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4391. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4392. leftValue = LoadValue(leftValue);
  4393. rightValue = LoadValue(rightValue);
  4394. EmitEquals(leftValue, rightValue, exitBB, false);
  4395. bool hadComparison = false;
  4396. for (auto& fieldRef : mCurTypeInstance->mFieldInstances)
  4397. {
  4398. BfFieldInstance* fieldInstance = &fieldRef;
  4399. if (fieldInstance->mDataOffset == -1)
  4400. continue;
  4401. auto fieldType = fieldInstance->mResolvedType;
  4402. if (fieldType->IsValuelessType())
  4403. continue;
  4404. if (fieldType->IsVar())
  4405. continue;
  4406. if (fieldType->IsMethodRef())
  4407. continue;
  4408. if (fieldType->IsRef())
  4409. fieldType = CreatePointerType(fieldType->GetUnderlyingType());
  4410. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(leftTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4411. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rightTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4412. if (!fieldInstance->mResolvedType->IsComposite())
  4413. {
  4414. leftValue = LoadValue(leftValue);
  4415. rightValue = LoadValue(rightValue);
  4416. }
  4417. EmitEquals(leftValue, rightValue, exitBB, false);
  4418. }
  4419. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4420. mBfIRBuilder->CreateBr(exitBB);
  4421. mBfIRBuilder->AddBlock(exitBB);
  4422. mBfIRBuilder->SetInsertPoint(exitBB);
  4423. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4424. ClearLifetimeEnds();
  4425. mBfIRBuilder->CreateRet(loadedResult);
  4426. mCurMethodState->mHadReturn = true;
  4427. }
  4428. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  4429. {
  4430. if (mCurMethodInstance->mIsUnspecialized)
  4431. return;
  4432. if (mBfIRBuilder->mIgnoreWrites)
  4433. return;
  4434. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  4435. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  4436. bool isValid = true;
  4437. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4438. if (compareType->IsValuelessType())
  4439. {
  4440. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4441. return;
  4442. }
  4443. if (compareType->IsTypedPrimitive())
  4444. {
  4445. BfExprEvaluator exprEvaluator(this);
  4446. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  4447. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  4448. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  4449. mBfIRBuilder->CreateRet(cmpResult);
  4450. return;
  4451. }
  4452. auto compareDType = compareType->ToDependedType();
  4453. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  4454. if (compareTypeInst != NULL)
  4455. {
  4456. if (compareType->IsPrimitiveType())
  4457. compareTypeInst = GetWrappedStructType(compareType);
  4458. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  4459. {
  4460. isValid = false;
  4461. }
  4462. mBfIRBuilder->PopulateType(compareTypeInst);
  4463. }
  4464. if (!isValid)
  4465. {
  4466. ClearLifetimeEnds();
  4467. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4468. return;
  4469. }
  4470. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  4471. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4472. if (refNode == NULL)
  4473. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4474. UpdateSrcPos(refNode);
  4475. SetIllegalSrcPos();
  4476. auto resultVal = CreateAlloca(boolType);
  4477. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4478. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4479. if (compareType->IsValuelessType())
  4480. {
  4481. // Always equal, nothing to do
  4482. }
  4483. else if (compareType->IsSizedArray())
  4484. {
  4485. auto sizedArrayType = (BfSizedArrayType*)compareType;
  4486. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  4487. {
  4488. BfTypedValue result;
  4489. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index, true);
  4490. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4491. if (!result.mType->IsValueType())
  4492. result = LoadValue(result);
  4493. return result;
  4494. };
  4495. if (sizedArrayType->mElementCount > 6)
  4496. {
  4497. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4498. auto itr = CreateAlloca(intPtrType);
  4499. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  4500. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  4501. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  4502. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  4503. mBfIRBuilder->CreateBr(loopBB);
  4504. mBfIRBuilder->SetInsertPoint(loopBB);
  4505. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  4506. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  4507. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  4508. mBfIRBuilder->SetInsertPoint(bodyBB);
  4509. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  4510. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  4511. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4512. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  4513. mBfIRBuilder->CreateStore(incValue, itr);
  4514. mBfIRBuilder->CreateBr(loopBB);
  4515. mBfIRBuilder->SetInsertPoint(doneBB);
  4516. }
  4517. else
  4518. {
  4519. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  4520. {
  4521. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4522. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4523. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4524. }
  4525. }
  4526. }
  4527. else if (compareType->IsMethodRef())
  4528. {
  4529. auto methodRefType = (BfMethodRefType*)compareType;
  4530. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  4531. BfExprEvaluator exprEvaluator(this);
  4532. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4533. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4534. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  4535. // values for the same method reference -- they will always refer back to the same local variables.
  4536. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  4537. if (dataIdx != -1)
  4538. {
  4539. bool failed = false;
  4540. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  4541. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  4542. BF_ASSERT(!failed);
  4543. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4544. }
  4545. }
  4546. else if (compareTypeInst->IsEnum())
  4547. {
  4548. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4549. BfExprEvaluator exprEvaluator(this);
  4550. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4551. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4552. auto dscrType = compareTypeInst->GetDiscriminatorType();
  4553. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  4554. leftValue = LoadValue(leftValue);
  4555. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  4556. rightValue = LoadValue(rightValue);
  4557. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  4558. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  4559. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4560. int enumCount = 0;
  4561. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4562. {
  4563. BfFieldInstance* fieldInstance = &fieldRef;
  4564. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4565. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4566. {
  4567. enumCount = -fieldInstance->mDataIdx;
  4568. }
  4569. }
  4570. if (enumCount > 0)
  4571. {
  4572. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  4573. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  4574. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4575. {
  4576. BfFieldInstance* fieldInstance = &fieldRef;
  4577. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4578. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4579. {
  4580. int enumIdx = -fieldInstance->mDataIdx - 1;
  4581. if (fieldInstance->mResolvedType->mSize == 0)
  4582. {
  4583. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  4584. }
  4585. else
  4586. {
  4587. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  4588. mBfIRBuilder->SetInsertPoint(caseBlock);
  4589. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  4590. BfTypedValue leftTuple;
  4591. BfTypedValue rightTuple;
  4592. if (leftPayload.IsAddr())
  4593. {
  4594. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4595. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4596. }
  4597. else
  4598. {
  4599. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4600. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4601. }
  4602. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  4603. mBfIRBuilder->CreateBr(matchedBlock);
  4604. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  4605. }
  4606. }
  4607. }
  4608. mBfIRBuilder->AddBlock(matchedBlock);
  4609. mBfIRBuilder->SetInsertPoint(matchedBlock);
  4610. }
  4611. }
  4612. else if (compareTypeInst->IsUnion())
  4613. {
  4614. auto innerType = compareTypeInst->GetUnionInnerType();
  4615. if (!innerType->IsValuelessType())
  4616. {
  4617. BfExprEvaluator exprEvaluator(this);
  4618. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4619. leftTypedVal = AggregateSplat(leftTypedVal);
  4620. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  4621. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4622. rightTypedVal = AggregateSplat(rightTypedVal);
  4623. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  4624. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  4625. }
  4626. }
  4627. else
  4628. {
  4629. BfExprEvaluator exprEvaluator(this);
  4630. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4631. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4632. bool hadComparison = false;
  4633. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4634. {
  4635. BfFieldInstance* fieldInstance = &fieldRef;
  4636. if (fieldInstance->mDataOffset == -1)
  4637. continue;
  4638. if (fieldInstance->mResolvedType->IsValuelessType())
  4639. continue;
  4640. if (fieldInstance->mResolvedType->IsVar())
  4641. continue;
  4642. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4643. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4644. if (!fieldInstance->mResolvedType->IsComposite())
  4645. {
  4646. leftValue = LoadValue(leftValue);
  4647. rightValue = LoadValue(rightValue);
  4648. }
  4649. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4650. }
  4651. auto baseTypeInst = compareTypeInst->mBaseType;
  4652. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  4653. {
  4654. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  4655. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  4656. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4657. }
  4658. }
  4659. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4660. mBfIRBuilder->CreateBr(exitBB);
  4661. mBfIRBuilder->AddBlock(exitBB);
  4662. mBfIRBuilder->SetInsertPoint(exitBB);
  4663. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4664. ClearLifetimeEnds();
  4665. mBfIRBuilder->CreateRet(loadedResult);
  4666. mCurMethodState->mHadReturn = true;
  4667. }
  4668. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  4669. {
  4670. if (mBfIRBuilder->mIgnoreWrites)
  4671. return mBfIRBuilder->GetFakeVal();
  4672. PopulateType(typeInstance, mIsComptimeModule ? BfPopulateType_Data : BfPopulateType_DataAndMethods);
  4673. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4674. if (mIsComptimeModule)
  4675. {
  4676. auto idVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, typeInstance->mTypeId);
  4677. return mBfIRBuilder->CreateIntToPtr(idVal, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4678. }
  4679. BfIRValue* globalVariablePtr = NULL;
  4680. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  4681. int numElements = 1;
  4682. if (mSystem->mPtrSize == 4)
  4683. numElements++;
  4684. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  4685. {
  4686. numElements += mCompiler->mMaxInterfaceSlots;
  4687. auto maxIFaceVirtIdx = 0;
  4688. if (!typeInstance->IsInterface())
  4689. {
  4690. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4691. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4692. numElements += typeInstance->GetOrigVTableSize();
  4693. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  4694. if (typeInstance->mHotTypeData != NULL)
  4695. {
  4696. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4697. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4698. }
  4699. numElements += ifaceMethodLen;
  4700. }
  4701. if (outNumElements != NULL)
  4702. *outNumElements = numElements;
  4703. }
  4704. StringT<128> classVDataName;
  4705. String memberName = "sBfClassVData";
  4706. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  4707. {
  4708. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  4709. memberName += "_";
  4710. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  4711. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  4712. }
  4713. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  4714. if (outMangledName != NULL)
  4715. *outMangledName = classVDataName;
  4716. BfIRValue globalVariable;
  4717. if (globalVariablePtr != NULL)
  4718. {
  4719. globalVariable = *globalVariablePtr;
  4720. }
  4721. else
  4722. {
  4723. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4724. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4725. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4726. arrayType,
  4727. true,
  4728. BfIRLinkageType_External,
  4729. BfIRValue(),
  4730. classVDataName);
  4731. mClassVDataRefs[typeInstance] = globalVariable;
  4732. }
  4733. return globalVariable;
  4734. }
  4735. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4736. {
  4737. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4738. if (mIsComptimeModule)
  4739. return mBfIRBuilder->Comptime_GetBfType(typeInstance->mTypeId, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4740. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4741. }
  4742. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4743. {
  4744. if (mBfIRBuilder->mIgnoreWrites)
  4745. return mBfIRBuilder->GetFakeVal();
  4746. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4747. BF_ASSERT(numElements >= 0);
  4748. if (numElements <= 0)
  4749. return BfIRValue();
  4750. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4751. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4752. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4753. BF_ASSERT(declTypeInst == implTypeInst);
  4754. else
  4755. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4756. if (declTypeInst != implTypeInst)
  4757. {
  4758. BfTypeInstance* highestImpl = declTypeInst;
  4759. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4760. {
  4761. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4762. break; // Start of an ext entry for another type
  4763. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4764. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4765. highestImpl = checkImplTypeInst;
  4766. }
  4767. if (highestImpl != implTypeInst)
  4768. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4769. }
  4770. BfVDataExtEntry mapEntry;
  4771. mapEntry.mDeclTypeInst = declTypeInst;
  4772. mapEntry.mImplTypeInst = implTypeInst;
  4773. BfIRValue* irValuePtr = NULL;
  4774. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4775. return *irValuePtr;
  4776. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4777. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4778. StringT<512> classVDataName;
  4779. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4780. if (declTypeInst != implTypeInst)
  4781. {
  4782. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4783. }
  4784. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4785. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4786. SizedArray<BfIRValue, 32> vData;
  4787. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4788. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4789. {
  4790. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4791. break; // Start of an ext entry for another type
  4792. BfIRValue vValue;
  4793. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4794. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4795. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4796. {
  4797. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4798. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4799. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4800. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4801. {
  4802. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4803. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4804. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4805. vValue = funcPtr;
  4806. }
  4807. }
  4808. if (!vValue)
  4809. vValue = voidPtrNull;
  4810. vData.Add(vValue);
  4811. }
  4812. BF_ASSERT((int)vData.size() == numElements);
  4813. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4814. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4815. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4816. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4817. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4818. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, vData);
  4819. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4820. mClassVDataExtRefs[mapEntry] = globalVariable;
  4821. return globalVariable;
  4822. }
  4823. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  4824. {
  4825. if (mBfIRBuilder->mIgnoreWrites)
  4826. {
  4827. return mBfIRBuilder->CreateTypeOf(type);
  4828. }
  4829. if (mIsComptimeModule)
  4830. {
  4831. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4832. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4833. return mBfIRBuilder->Comptime_GetReflectType(type->mTypeId, mBfIRBuilder->MapType(typeTypeInst));
  4834. }
  4835. PopulateType(type);
  4836. BfIRValue globalVariable;
  4837. BfIRValue* globalVariablePtr = NULL;
  4838. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  4839. {
  4840. if (*globalVariablePtr)
  4841. return mBfIRBuilder->CreateTypeOf(type, *globalVariablePtr);
  4842. }
  4843. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4844. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4845. auto typeInstance = type->ToTypeInstance();
  4846. StringT<4096> typeDataName;
  4847. if (typeInstance != NULL)
  4848. {
  4849. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4850. }
  4851. else
  4852. {
  4853. typeDataName += "sBfTypeData.";
  4854. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  4855. }
  4856. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  4857. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  4858. mBfIRBuilder->SetReflectTypeData(mBfIRBuilder->MapType(type), globalVariable);
  4859. mTypeDataRefs[type] = globalVariable;
  4860. return mBfIRBuilder->CreateTypeOf(type, globalVariable);
  4861. }
  4862. void BfModule::EncodeAttributeData(BfTypeInstance* typeInstance, BfType* argType, BfIRValue arg, SizedArrayImpl<uint8>& data, Dictionary<int, int>& usedStringIdMap)
  4863. {
  4864. #define PUSH_INT8(val) data.push_back((uint8)val)
  4865. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4866. #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); }
  4867. #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); \
  4868. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4869. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4870. bool handled = false;
  4871. if (constant == NULL)
  4872. {
  4873. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  4874. return;
  4875. }
  4876. if (argType->IsObject())
  4877. {
  4878. if ((argType->IsInstanceOf(mCompiler->mStringTypeDef)) || (argType == mContext->mBfObjectType))
  4879. {
  4880. if (constant->mTypeCode == BfTypeCode_StringId)
  4881. {
  4882. int stringId = constant->mInt32;
  4883. int* orderedIdPtr;
  4884. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4885. {
  4886. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4887. }
  4888. GetStringObjectValue(stringId, true, true);
  4889. PUSH_INT8(0xFF); // String
  4890. PUSH_INT32(*orderedIdPtr);
  4891. return;
  4892. }
  4893. }
  4894. }
  4895. if (argType->IsPointer())
  4896. {
  4897. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  4898. {
  4899. if (constant->mTypeCode == BfTypeCode_StringId)
  4900. {
  4901. int stringId = constant->mInt32;
  4902. int* orderedIdPtr;
  4903. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4904. {
  4905. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4906. }
  4907. GetStringObjectValue(stringId, true, true);
  4908. PUSH_INT8(0xFF); // String
  4909. PUSH_INT32(*orderedIdPtr);
  4910. return;
  4911. }
  4912. }
  4913. }
  4914. if (constant->mConstType == BfConstType_BitCastNull)
  4915. {
  4916. PUSH_INT8(BfTypeCode_NullPtr);
  4917. return;
  4918. }
  4919. if (constant->mConstType == BfConstType_BitCast)
  4920. {
  4921. auto bitcast = (BfConstantBitCast*)constant;
  4922. EncodeAttributeData(typeInstance, argType, BfIRValue(BfIRValueFlags_Const, bitcast->mTarget), data, usedStringIdMap);
  4923. return;
  4924. }
  4925. PUSH_INT8(constant->mTypeCode);
  4926. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4927. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4928. (constant->mTypeCode == BfTypeCode_Double))
  4929. {
  4930. PUSH_INT64(constant->mInt64);
  4931. }
  4932. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4933. (constant->mTypeCode == BfTypeCode_UInt32) ||
  4934. (constant->mTypeCode == BfTypeCode_Char32))
  4935. {
  4936. PUSH_INT32(constant->mInt32);
  4937. }
  4938. else if (constant->mTypeCode == BfTypeCode_Float)
  4939. {
  4940. float val = (float)constant->mDouble;
  4941. PUSH_INT32(*(int*)&val);
  4942. }
  4943. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4944. (constant->mTypeCode == BfTypeCode_UInt16) ||
  4945. (constant->mTypeCode == BfTypeCode_Char16))
  4946. {
  4947. PUSH_INT16(constant->mInt16);
  4948. }
  4949. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4950. (constant->mTypeCode == BfTypeCode_UInt8) ||
  4951. (constant->mTypeCode == BfTypeCode_Boolean) ||
  4952. (constant->mTypeCode == BfTypeCode_Char8))
  4953. {
  4954. PUSH_INT8(constant->mInt8);
  4955. }
  4956. else if (constant->mConstType == BfConstType_TypeOf)
  4957. {
  4958. auto typeOf = (BfTypeOf_Const*)constant;
  4959. PUSH_INT32(typeOf->mType->mTypeId);
  4960. }
  4961. else if (constant->mConstType == BfConstType_AggZero)
  4962. {
  4963. for (int i = 0; i < argType->mSize; i++)
  4964. data.Add(0);
  4965. }
  4966. else if (constant->mConstType == BfConstType_Box)
  4967. {
  4968. auto box = (BfConstantBox*)constant;
  4969. PUSH_INT32(box->mToType.mId);
  4970. BfType* resultType = NULL;
  4971. if (box->mToType.mKind == BfIRTypeData::TypeKind_TypeId)
  4972. resultType = mContext->FindTypeById(box->mToType.mId);
  4973. if ((resultType != NULL) && (resultType->IsBoxed()))
  4974. {
  4975. auto boxedType = (BfBoxedType*)resultType;
  4976. int dataOffset = 0;
  4977. if (!boxedType->mFieldInstances.IsEmpty())
  4978. dataOffset = BF_MAX(boxedType->mFieldInstances.back().mDataOffset, 0);
  4979. int dataSize = boxedType->mInstSize - dataOffset;
  4980. for (int i = 0; i < dataSize; i++)
  4981. data.Add(0);
  4982. typeInstance->mConstHolder->WriteConstant(BfIRValue(BfIRValueFlags_Const, box->mTarget), &data[data.mSize - dataSize], boxedType->GetUnderlyingType());
  4983. return;
  4984. }
  4985. //int dataOffset =
  4986. //mBfIRBuilder->WriteConstant()
  4987. // BfType* resultType = NULL;
  4988. // if (box->mToType.mKind == BfIRTypeData::TypeKind_TypeId)
  4989. // resultType = mContext->FindTypeById(box->mToType.mId);
  4990. //
  4991. // if ((resultType != NULL) && (resultType->IsBoxed()))
  4992. // {
  4993. // auto boxedType = (BfBoxedType*)resultType;
  4994. // EncodeAttributeData(typeInstance, boxedType->GetUnderlyingType(), BfIRValue(BfIRValueFlags_Const, box->mTarget), data, usedStringIdMap);
  4995. // return;
  4996. // }
  4997. Fail(StrFormat("Unhandled constant box in '%s'", TypeToString(typeInstance).c_str()));
  4998. }
  4999. // else if (constant->mConstType == BfConstType_Agg)
  5000. // {
  5001. // BF_ASSERT(argType->IsComposite());
  5002. // if (argType->IsSizedArray())
  5003. // {
  5004. // auto argSizedArrayType = (BfSizedArrayType*)argType;
  5005. // }
  5006. // else
  5007. // {
  5008. // auto argTypeInstance = argType->ToTypeInstance();
  5009. // }
  5010. // }
  5011. else
  5012. {
  5013. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  5014. }
  5015. }
  5016. BfIRValue BfModule::CreateFieldData(BfFieldInstance* fieldInstance, int customAttrIdx)
  5017. {
  5018. bool isComptimeArg = mBfIRBuilder->mIgnoreWrites;
  5019. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5020. auto typeInstance = fieldInstance->mOwner;
  5021. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5022. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5023. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5024. BfType* typeIdType = intType;
  5025. BfTypeInstance* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef)->ToTypeInstance();
  5026. BfIRValue emptyValueType = mBfIRBuilder->mIgnoreWrites ?
  5027. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>()) :
  5028. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>());
  5029. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, !mIsComptimeModule);
  5030. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  5031. int typeId = 0;
  5032. auto fieldType = fieldInstance->GetResolvedType();
  5033. if (fieldType->IsGenericParam())
  5034. {
  5035. //TODO:
  5036. }
  5037. else
  5038. typeId = fieldType->mTypeId;
  5039. BfFieldFlags fieldFlags = (BfFieldFlags)0;
  5040. if (fieldDef->mProtection == BfProtection_Protected)
  5041. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Protected);
  5042. if (fieldDef->mProtection == BfProtection_Public)
  5043. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Public);
  5044. if (fieldDef->mIsStatic)
  5045. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Static);
  5046. if (fieldDef->mIsConst)
  5047. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Const);
  5048. if (fieldDef->IsEnumCaseEntry())
  5049. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_EnumCase);
  5050. if (fieldDef->mIsReadOnly)
  5051. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_ReadOnly);
  5052. if (fieldInstance->IsAppendedObject())
  5053. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Appended);
  5054. BfIRValue constValue;
  5055. BfIRValue constValue2;
  5056. if (fieldInstance->mIsEnumPayloadCase)
  5057. {
  5058. int tagId = -fieldInstance->mDataIdx - 1;
  5059. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, tagId);
  5060. }
  5061. else if (fieldInstance->GetFieldDef()->mIsConst)
  5062. {
  5063. if (fieldInstance->mConstIdx != -1)
  5064. {
  5065. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  5066. uint64 val = constant->mUInt64;
  5067. if (constant->mTypeCode == BfTypeCode_Float)
  5068. {
  5069. float f = (float)*(double*)&val;
  5070. val = *(uint32*)&f;
  5071. }
  5072. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5073. if (is32Bit)
  5074. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val >> 32);
  5075. }
  5076. }
  5077. else if (fieldInstance->GetFieldDef()->mIsStatic)
  5078. {
  5079. BfTypedValue refVal;
  5080. if (mIsComptimeModule)
  5081. {
  5082. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mFieldIdx);
  5083. }
  5084. else
  5085. {
  5086. refVal = ReferenceStaticField(fieldInstance);
  5087. }
  5088. if (refVal.mValue.IsConst())
  5089. {
  5090. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  5091. if (constant->mConstType == BfConstType_GlobalVar)
  5092. {
  5093. auto globalVar = (BfGlobalVar*)constant;
  5094. if (globalVar->mName[0] == '#')
  5095. refVal = BfTypedValue();
  5096. }
  5097. }
  5098. if (!isComptimeArg)
  5099. {
  5100. if (refVal.IsAddr())
  5101. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5102. else if ((fieldInstance->IsAppendedObject()) && (refVal))
  5103. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5104. }
  5105. }
  5106. if (!constValue)
  5107. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  5108. BfIRValue result;
  5109. if (is32Bit)
  5110. {
  5111. if (!constValue2)
  5112. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  5113. SizedArray<BfIRValue, 8> fieldVals =
  5114. {
  5115. emptyValueType,
  5116. fieldNameConst, // mName
  5117. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5118. constValue, // mData
  5119. constValue2, // mDataHi
  5120. GetConstValue(fieldFlags, shortType), // mFlags
  5121. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5122. };
  5123. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5124. result = isComptimeArg ?
  5125. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5126. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5127. }
  5128. else
  5129. {
  5130. SizedArray<BfIRValue, 8> fieldVals =
  5131. {
  5132. emptyValueType,
  5133. fieldNameConst, // mName
  5134. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5135. constValue, // mData
  5136. GetConstValue(fieldFlags, shortType), // mFlags
  5137. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5138. };
  5139. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5140. result = isComptimeArg ?
  5141. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5142. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5143. }
  5144. return result;
  5145. }
  5146. void BfModule::CreateSlotOfs(BfTypeInstance* typeInstance)
  5147. {
  5148. int virtSlotIdx = -1;
  5149. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5150. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5151. // For interfaces we ONLY emit the slot num
  5152. StringT<512> slotVarName;
  5153. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  5154. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  5155. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  5156. GetConstValue32(virtSlotIdx), slotVarName);
  5157. }
  5158. BfIRValue BfModule::CreateTypeData(BfType* type, BfCreateTypeDataContext& ctx, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  5159. {
  5160. if ((IsHotCompile()) && (!type->mDirty))
  5161. return BfIRValue();
  5162. BfIRValue* irValuePtr = NULL;
  5163. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  5164. {
  5165. return *irValuePtr;
  5166. }
  5167. BfTypeInstance* typeInstance = type->ToTypeInstance();
  5168. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  5169. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  5170. if (typeInstanceType == NULL)
  5171. {
  5172. AssertErrorState();
  5173. return BfIRValue();
  5174. }
  5175. BfIRValue typeTypeData;
  5176. int typeFlags = 0;
  5177. if (needsTypeData)
  5178. {
  5179. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  5180. BfTypeInstance* typeDataSource = NULL;
  5181. if (typeInstance != NULL)
  5182. {
  5183. if (typeInstance->IsUnspecializedType())
  5184. {
  5185. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  5186. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  5187. }
  5188. else if (typeInstance->IsArray())
  5189. {
  5190. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  5191. typeFlags |= BfTypeFlags_Array;
  5192. }
  5193. else if (typeInstance->IsGenericTypeInstance())
  5194. {
  5195. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  5196. typeFlags |= BfTypeFlags_SpecializedGeneric;
  5197. }
  5198. else
  5199. typeDataSource = typeInstanceTypeInstance;
  5200. }
  5201. else if (type->IsPointer())
  5202. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5203. else if (type->IsRef())
  5204. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5205. else if (type->IsSizedArray())
  5206. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5207. else if (type->IsConstExprValue())
  5208. typeDataSource = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5209. else if (type->IsGenericParam())
  5210. {
  5211. typeFlags |= BfTypeFlags_GenericParam;
  5212. typeDataSource = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5213. }
  5214. else
  5215. typeDataSource = mContext->mBfTypeType;
  5216. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type) && (!mIsComptimeModule))
  5217. {
  5218. CreateTypeData(typeDataSource, ctx, false, true, needsTypeNames, true);
  5219. }
  5220. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  5221. ctx.mReflectTypeSet.Add(typeDataSource);
  5222. }
  5223. else
  5224. {
  5225. //typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  5226. typeTypeData = mBfIRBuilder->CreateConstNull();
  5227. }
  5228. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5229. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5230. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5231. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5232. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5233. BfType* typeIdType = intType;
  5234. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  5235. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  5236. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  5237. auto voidPtrNull = GetDefaultValue(voidPtrType);
  5238. SizedArray<BfIRValue, 4> typeValueParams;
  5239. GetConstClassValueParam(typeTypeData, typeValueParams);
  5240. FixConstValueParams(mContext->mBfObjectType, typeValueParams);
  5241. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5242. StringT<512> typeDataName;
  5243. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  5244. {
  5245. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  5246. if (typeInstance->mTypeDef->IsGlobalsContainer())
  5247. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  5248. }
  5249. else
  5250. {
  5251. typeDataName += "sBfTypeData.";
  5252. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  5253. }
  5254. int typeCode = BfTypeCode_None;
  5255. if (typeInstance != NULL)
  5256. {
  5257. BF_ASSERT((type->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || mIsComptimeModule);
  5258. typeCode = typeInstance->mTypeDef->mTypeCode;
  5259. if (typeInstance->IsBoxed())
  5260. typeCode = BfTypeCode_Object;
  5261. }
  5262. else if (type->IsPrimitiveType())
  5263. {
  5264. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  5265. typeCode = primType->mTypeDef->mTypeCode;
  5266. }
  5267. else if (type->IsPointer())
  5268. {
  5269. typeCode = BfTypeCode_Pointer;
  5270. typeFlags |= BfTypeFlags_Pointer;
  5271. }
  5272. else if (type->IsRef())
  5273. {
  5274. typeCode = BfTypeCode_Pointer;
  5275. typeFlags |= BfTypeFlags_Pointer;
  5276. }
  5277. if (type->IsObject())
  5278. {
  5279. typeFlags |= BfTypeFlags_Object;
  5280. if (typeInstance->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted)
  5281. {
  5282. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  5283. if ((methodInstance != NULL) && (methodInstance->GetOwner() != mContext->mBfObjectType))
  5284. typeFlags |= BfTypeFlags_HasDestructor;
  5285. }
  5286. }
  5287. if (type->IsStruct())
  5288. typeFlags |= BfTypeFlags_Struct;
  5289. if (type->IsInterface())
  5290. typeFlags |= BfTypeFlags_Interface;
  5291. if (type->IsBoxed())
  5292. {
  5293. typeFlags |= BfTypeFlags_Boxed;
  5294. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  5295. typeFlags |= BfTypeFlags_Pointer;
  5296. }
  5297. if (type->IsPrimitiveType())
  5298. typeFlags |= BfTypeFlags_Primitive;
  5299. if (type->IsTypedPrimitive())
  5300. typeFlags |= BfTypeFlags_TypedPrimitive;
  5301. if (type->IsTuple())
  5302. typeFlags |= BfTypeFlags_Tuple;
  5303. if (type->IsNullable())
  5304. typeFlags |= BfTypeFlags_Nullable;
  5305. if (type->IsSizedArray())
  5306. typeFlags |= BfTypeFlags_SizedArray;
  5307. if (type->IsConstExprValue())
  5308. typeFlags |= BfTypeFlags_ConstExpr;
  5309. if (type->IsSplattable())
  5310. typeFlags |= BfTypeFlags_Splattable;
  5311. if (type->IsUnion())
  5312. typeFlags |= BfTypeFlags_Union;
  5313. if (type->IsDelegate())
  5314. typeFlags |= BfTypeFlags_Delegate;
  5315. if (type->IsFunction())
  5316. typeFlags |= BfTypeFlags_Function;
  5317. if ((type->mDefineState != BfTypeDefineState_CETypeInit) && (type->WantsGCMarking()))
  5318. typeFlags |= BfTypeFlags_WantsMarking;
  5319. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsStatic))
  5320. typeFlags |= BfTypeFlags_Static;
  5321. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  5322. typeFlags |= BfTypeFlags_Abstract;
  5323. int virtSlotIdx = -1;
  5324. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5325. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5326. int memberDataOffset = 0;
  5327. if (type->IsInterface())
  5328. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  5329. else if (typeInstance != NULL)
  5330. {
  5331. for (auto& fieldInstance : typeInstance->mFieldInstances)
  5332. {
  5333. if (fieldInstance.mDataOffset != -1)
  5334. {
  5335. memberDataOffset = fieldInstance.mDataOffset;
  5336. break;
  5337. }
  5338. }
  5339. }
  5340. int boxedTypeId = 0;
  5341. if ((type->IsValueType()) || (type->IsWrappableType()))
  5342. {
  5343. auto boxedType = CreateBoxedType(type, false);
  5344. if ((boxedType != NULL) && (boxedType->mIsReified))
  5345. boxedTypeId = boxedType->mTypeId;
  5346. }
  5347. int stackCount = 0;
  5348. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  5349. {
  5350. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5351. if (typeOptions->mAllocStackTraceDepth != -1)
  5352. stackCount = BF_MIN(0xFF, BF_MAX(0x01, typeOptions->mAllocStackTraceDepth));
  5353. }
  5354. SizedArray<BfIRValue, 9> typeDataParams =
  5355. {
  5356. objectData,
  5357. GetConstValue(type->mSize, intType), // mSize
  5358. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5359. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  5360. GetConstValue(typeFlags, intType), // mTypeFlags
  5361. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  5362. GetConstValue(typeCode, byteType), // mTypeCode
  5363. GetConstValue(type->mAlign, byteType), // mAlign
  5364. GetConstValue(stackCount, byteType), // mAllocStackCountOverride
  5365. };
  5366. FixConstValueParams(mContext->mBfTypeType, typeDataParams);
  5367. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  5368. if (typeInstance == NULL)
  5369. {
  5370. BfIRValue typeDataVar;
  5371. if (needsTypeData)
  5372. {
  5373. if (type->IsPointer())
  5374. {
  5375. auto pointerType = (BfPointerType*)type;
  5376. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  5377. {
  5378. typeData,
  5379. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  5380. };
  5381. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5382. FixConstValueParams(reflectPointerType, pointerTypeDataParms);
  5383. auto pointerTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  5384. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  5385. BfIRLinkageType_External, pointerTypeData, typeDataName);
  5386. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5387. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5388. }
  5389. else if (type->IsRef())
  5390. {
  5391. auto refType = (BfRefType*)type;
  5392. SizedArray<BfIRValue, 3> refTypeDataParms =
  5393. {
  5394. typeData,
  5395. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  5396. GetConstValue((int8)refType->mRefKind, byteType),
  5397. };
  5398. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5399. FixConstValueParams(reflectRefType, refTypeDataParms);
  5400. auto refTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  5401. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  5402. BfIRLinkageType_External, refTypeData, typeDataName);
  5403. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5404. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5405. }
  5406. else if (type->IsSizedArray())
  5407. {
  5408. auto sizedArrayType = (BfSizedArrayType*)type;
  5409. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  5410. {
  5411. typeData,
  5412. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  5413. GetConstValue(sizedArrayType->mElementCount, intType)
  5414. };
  5415. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5416. FixConstValueParams(reflectSizedArrayType, sizedArrayTypeDataParms);
  5417. auto sizedArrayTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  5418. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  5419. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  5420. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5421. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5422. }
  5423. else if (type->IsConstExprValue())
  5424. {
  5425. auto constExprType = (BfConstExprValueType*)type;
  5426. SizedArray<BfIRValue, 3> constExprTypeDataParms =
  5427. {
  5428. typeData,
  5429. GetConstValue(constExprType->mType->mTypeId, typeIdType),
  5430. GetConstValue(constExprType->mValue.mInt64, longType)
  5431. };
  5432. auto reflectConstExprType = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5433. FixConstValueParams(reflectConstExprType, constExprTypeDataParms);
  5434. auto ConstExprTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectConstExprType, BfIRPopulateType_Full), constExprTypeDataParms);
  5435. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectConstExprType), true,
  5436. BfIRLinkageType_External, ConstExprTypeData, typeDataName);
  5437. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5438. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5439. }
  5440. else if (type->IsGenericParam())
  5441. {
  5442. auto genericParamType = (BfGenericParamType*)type;
  5443. SizedArray<BfIRValue, 3> genericParamTypeDataParms =
  5444. {
  5445. typeData
  5446. };
  5447. auto reflectGenericParamType = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5448. FixConstValueParams(reflectGenericParamType, genericParamTypeDataParms);
  5449. auto genericParamTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectGenericParamType, BfIRPopulateType_Full), genericParamTypeDataParms);
  5450. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectGenericParamType), true,
  5451. BfIRLinkageType_External, genericParamTypeData, typeDataName);
  5452. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5453. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5454. }
  5455. else
  5456. {
  5457. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  5458. BfIRLinkageType_External, typeData, typeDataName);
  5459. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5460. }
  5461. }
  5462. else
  5463. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5464. mTypeDataRefs[type] = typeDataVar;
  5465. return typeDataVar;
  5466. }
  5467. // Reserve position
  5468. mTypeDataRefs[typeInstance] = BfIRValue();
  5469. if ((typeInstance->IsReified()) && (!mIsComptimeModule))
  5470. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5471. BfTypeDef* typeDef = typeInstance->mTypeDef;
  5472. StringT<512> mangledName;
  5473. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  5474. if (!mIsComptimeModule)
  5475. {
  5476. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5477. {
  5478. auto methodDef = typeDef->mMethods[methodIdx];
  5479. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  5480. if (methodInstance == NULL)
  5481. continue;
  5482. if (typeInstance->IsUnspecializedType())
  5483. continue;
  5484. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5485. {
  5486. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  5487. {
  5488. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  5489. // We need to create an empty thunk for this chained method
  5490. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  5491. mBfIRBuilder->SetActiveFunction(func);
  5492. auto block = mBfIRBuilder->CreateBlock("entry", true);
  5493. mBfIRBuilder->SetInsertPoint(block);
  5494. mBfIRBuilder->CreateRetVoid();
  5495. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  5496. }
  5497. }
  5498. }
  5499. }
  5500. SizedArray<BfIRValue, 32> vData;
  5501. BfIRValue classVDataVar;
  5502. String classVDataName;
  5503. if (typeInstance->mSlotNum >= 0)
  5504. {
  5505. CreateSlotOfs(typeInstance);
  5506. }
  5507. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  5508. {
  5509. int dynCastDataElems = 0;
  5510. int numElements = 1;
  5511. int vDataOfs = mCompiler->GetVDataPrefixDataCount(); // The number of intptrs before the iface slot map
  5512. numElements += mCompiler->mMaxInterfaceSlots;
  5513. if (!typeInstance->IsInterface())
  5514. {
  5515. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  5516. numElements += mCompiler->GetDynCastVDataCount();
  5517. numElements += typeInstance->mVirtualMethodTableSize;
  5518. }
  5519. int expectNumElements = 0;
  5520. if (!typeDef->mIsStatic)
  5521. {
  5522. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  5523. }
  5524. for (int i = 0; i < mCompiler->GetVDataPrefixDataCount(); i++)
  5525. vData.push_back(BfIRValue()); // Type
  5526. SizedArray<BfIRValue, 1> extVTableData;
  5527. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  5528. if (!typeInstance->IsInterface())
  5529. {
  5530. Array<int32> dynCastData;
  5531. if (typeInstance->IsBoxed())
  5532. {
  5533. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  5534. dynCastData.Add(underlyingType->mInheritanceId);
  5535. }
  5536. else
  5537. dynCastData.Add(typeInstance->mInheritanceId);
  5538. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  5539. dynCastData.Add(0);
  5540. dynCastData.Add(0);
  5541. auto checkTypeInst = typeInstance;
  5542. while (checkTypeInst != NULL)
  5543. {
  5544. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5545. {
  5546. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  5547. {
  5548. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  5549. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  5550. }
  5551. }
  5552. checkTypeInst = checkTypeInst->GetImplBaseType();
  5553. }
  5554. if (mSystem->mPtrSize == 8)
  5555. {
  5556. int intPtrCount = (dynCastDataElems + 1) / 2;
  5557. vDataOfs += intPtrCount;
  5558. uint64* intPtrData = (uint64*)&dynCastData[0];
  5559. for (int i = 0; i < intPtrCount; i++)
  5560. {
  5561. uint64 val = intPtrData[i];
  5562. if (val == 0)
  5563. {
  5564. vData.push_back(voidPtrNull);
  5565. }
  5566. else
  5567. {
  5568. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5569. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5570. }
  5571. }
  5572. }
  5573. else
  5574. {
  5575. int intPtrCount = dynCastDataElems;
  5576. vDataOfs += intPtrCount;
  5577. uint32* intPtrData = (uint32*)&dynCastData[0];
  5578. for (int i = 0; i < intPtrCount; i++)
  5579. {
  5580. uint32 val = intPtrData[i];
  5581. if (val == 0)
  5582. {
  5583. vData.push_back(voidPtrNull);
  5584. }
  5585. else
  5586. {
  5587. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  5588. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5589. }
  5590. }
  5591. }
  5592. }
  5593. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  5594. vData.push_back(voidPtrNull);
  5595. struct _InterfaceMatchEntry
  5596. {
  5597. BfTypeInterfaceEntry* mEntry;
  5598. BfTypeInstance* mEntrySource;
  5599. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  5600. };
  5601. int highestIFaceVirtIdx = 0;
  5602. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  5603. auto checkTypeInst = typeInstance;
  5604. bool forceInterfaceSet = false;
  5605. while (checkTypeInst != NULL)
  5606. {
  5607. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5608. {
  5609. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  5610. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject)))
  5611. continue;
  5612. _InterfaceMatchEntry* matchEntry = NULL;
  5613. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  5614. {
  5615. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  5616. if (compareCheckTypeInst->IsBoxed())
  5617. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  5618. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  5619. if (compareEntrySource->IsBoxed())
  5620. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  5621. auto prevEntry = matchEntry->mEntry;
  5622. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  5623. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  5624. if ((!isBetter) && (!isWorse))
  5625. {
  5626. // Unboxed comparison to Object fix
  5627. if (compareCheckTypeInst == mContext->mBfObjectType)
  5628. isWorse = true;
  5629. else if (compareEntrySource == mContext->mBfObjectType)
  5630. isBetter = true;
  5631. }
  5632. if (forceInterfaceSet)
  5633. {
  5634. isBetter = true;
  5635. isWorse = false;
  5636. }
  5637. if (isBetter == isWorse)
  5638. CompareDeclTypes(checkTypeInst, interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  5639. if (isBetter == isWorse)
  5640. {
  5641. if (matchEntry->mAmbiguousEntries.empty())
  5642. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  5643. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  5644. continue;
  5645. }
  5646. else if (isBetter)
  5647. {
  5648. matchEntry->mEntry = &interfaceEntry;
  5649. matchEntry->mEntrySource = checkTypeInst;
  5650. matchEntry->mAmbiguousEntries.Clear();
  5651. }
  5652. else
  5653. continue;
  5654. }
  5655. else
  5656. {
  5657. _InterfaceMatchEntry matchEntry;
  5658. matchEntry.mEntry = &interfaceEntry;
  5659. matchEntry.mEntrySource = checkTypeInst;
  5660. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  5661. }
  5662. }
  5663. checkTypeInst = checkTypeInst->GetImplBaseType();
  5664. }
  5665. for (auto interfacePair : interfaceMap)
  5666. {
  5667. auto& interfaceMatchEntry = interfacePair.mValue;
  5668. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  5669. {
  5670. 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());
  5671. if (error != NULL)
  5672. {
  5673. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  5674. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  5675. }
  5676. }
  5677. }
  5678. if ((!mIsComptimeModule) && (!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  5679. {
  5680. int startTabIdx = (int)vData.size();
  5681. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  5682. BfTypeInstance* checkTypeInst = typeInstance;
  5683. while (checkTypeInst != NULL)
  5684. {
  5685. origVirtTypeStack.push_back(checkTypeInst);
  5686. checkTypeInst = checkTypeInst->GetImplBaseType();
  5687. }
  5688. Array<BfVirtualMethodEntry> origVTable;
  5689. int origVirtIdx = 0;
  5690. if (typeInstance->mTypeDef->mIsCombinedPartial)
  5691. {
  5692. HashSet<String> reslotNames;
  5693. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5694. {
  5695. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5696. if (entry.mDeclaringMethod.mMethodNum == -1)
  5697. continue;
  5698. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5699. if ((methodInstance == NULL) ||
  5700. ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))))
  5701. {
  5702. if (origVTable.empty())
  5703. origVTable = typeInstance->mVirtualMethodTable;
  5704. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  5705. if (declMethodInstance != NULL)
  5706. {
  5707. if ((mIsComptimeModule) || (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject)))
  5708. {
  5709. // Prepare to reslot...
  5710. entry.mImplementingMethod = entry.mDeclaringMethod;
  5711. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  5712. }
  5713. else
  5714. {
  5715. // Decl isn't accessible, null out entry
  5716. entry.mImplementingMethod = BfMethodRef();
  5717. }
  5718. }
  5719. }
  5720. }
  5721. if (!reslotNames.IsEmpty())
  5722. {
  5723. BfAmbiguityContext ambiguityContext;
  5724. ambiguityContext.mTypeInstance = typeInstance;
  5725. ambiguityContext.mModule = this;
  5726. ambiguityContext.mIsProjectSpecific = true;
  5727. ambiguityContext.mIsReslotting = true;
  5728. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5729. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  5730. {
  5731. auto methodInstance = methodGroup.mDefault;
  5732. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  5733. continue;
  5734. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  5735. continue;
  5736. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  5737. continue;
  5738. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  5739. continue;
  5740. SlotVirtualMethod(methodInstance, &ambiguityContext);
  5741. }
  5742. ambiguityContext.Finish();
  5743. }
  5744. }
  5745. bool isInExts = false;
  5746. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5747. {
  5748. BfIRValue vValue = voidPtrNull;
  5749. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5750. BfModuleMethodInstance moduleMethodInst;
  5751. if (entry.mDeclaringMethod.mMethodNum == -1)
  5752. {
  5753. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  5754. isInExts = true;
  5755. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  5756. if (vExt)
  5757. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  5758. }
  5759. else
  5760. {
  5761. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  5762. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  5763. {
  5764. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  5765. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  5766. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5767. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5768. {
  5769. BF_ASSERT((mIsComptimeModule) || typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  5770. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5771. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5772. vValue = funcPtr;
  5773. }
  5774. }
  5775. }
  5776. while (origVirtTypeStack.size() != 0)
  5777. {
  5778. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  5779. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  5780. {
  5781. // Moved past current base vtable size
  5782. origVirtTypeStack.pop_back();
  5783. continue;
  5784. }
  5785. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  5786. {
  5787. // We are within the original vtable size
  5788. int idx = startTabIdx + origVirtIdx;
  5789. origVirtIdx++;
  5790. vData.push_back(vValue);
  5791. }
  5792. else
  5793. {
  5794. // This is a new entry, it only gets added to the ext
  5795. BF_ASSERT(isInExts);
  5796. }
  5797. break;
  5798. }
  5799. }
  5800. if (!origVTable.empty())
  5801. typeInstance->mVirtualMethodTable = origVTable;
  5802. }
  5803. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  5804. if (typeInstance->mHotTypeData != NULL)
  5805. {
  5806. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  5807. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  5808. }
  5809. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  5810. int iFaceMethodStartIdx = (int)vData.size();
  5811. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  5812. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  5813. vData[i] = voidPtrNull;
  5814. if (expectNumElements != 0)
  5815. BF_ASSERT(expectNumElements == vData.size());
  5816. //BF_ASSERT(vData.size() == expectNumElements);
  5817. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  5818. // ifaceMethodExtData.Add(voidPtrNull);
  5819. int ifaceEntryIdx = iFaceMethodStartIdx;
  5820. for (auto& interfacePair : interfaceMap)
  5821. {
  5822. auto interfaceEntry = interfacePair.mValue.mEntry;
  5823. if (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  5824. {
  5825. BF_ASSERT(mIsComptimeModule);
  5826. break;
  5827. }
  5828. bool makeEmpty = false;
  5829. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject)))
  5830. makeEmpty = true;
  5831. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5832. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  5833. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5834. {
  5835. BfIRValue pushValue;
  5836. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5837. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5838. continue;
  5839. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5840. continue;
  5841. if (makeEmpty)
  5842. {
  5843. pushValue = voidPtrNull;
  5844. }
  5845. else
  5846. {
  5847. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5848. auto methodInstance = (BfMethodInstance*)methodRef;
  5849. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5850. {
  5851. BF_ASSERT(methodInstance->mIsReified);
  5852. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5853. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5854. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5855. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5856. pushValue = funcPtr;
  5857. }
  5858. else
  5859. {
  5860. pushValue = voidPtrNull;
  5861. }
  5862. }
  5863. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5864. if (idx < ifaceMethodExtStart)
  5865. {
  5866. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  5867. vData[iFaceMethodStartIdx + idx] = pushValue;
  5868. }
  5869. else
  5870. {
  5871. BF_ASSERT(useExt);
  5872. int extIdx = idx - ifaceMethodExtStart;
  5873. while (extIdx >= ifaceMethodExtData.size())
  5874. ifaceMethodExtData.Add(voidPtrNull);
  5875. ifaceMethodExtData[extIdx] = pushValue;
  5876. }
  5877. }
  5878. }
  5879. if (typeInstance->IsBoxed())
  5880. {
  5881. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  5882. if (boxedType->IsBoxedStructPtr())
  5883. {
  5884. // Force override of GetHashCode so we use the pointer address as the hash code
  5885. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  5886. // Force override of GetHashCode so we use the pointer address as the hash code
  5887. for (auto& checkIFace : checkTypeInst->mInterfaces)
  5888. {
  5889. if (checkIFace.mStartVirtualIdx < 0)
  5890. continue;
  5891. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5892. {
  5893. BfIRValue pushValue;
  5894. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5895. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5896. continue;
  5897. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5898. continue;
  5899. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5900. auto methodInstance = (BfMethodInstance*)methodRef;
  5901. BF_ASSERT(methodInstance->mIsReified);
  5902. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5903. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5904. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5905. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5906. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5907. vData[iFaceMethodStartIdx + idx] = funcPtr;
  5908. }
  5909. }
  5910. }
  5911. }
  5912. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic) && (!mIsComptimeModule))
  5913. {
  5914. BfIRValue ifaceMethodExtVar;
  5915. if ((!ifaceMethodExtData.IsEmpty()) && (!mIsComptimeModule))
  5916. {
  5917. StringT<512> classVDataName;
  5918. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  5919. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  5920. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  5921. BfIRLinkageType_External, BfIRValue(), classVDataName);
  5922. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  5923. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, ifaceMethodExtData);
  5924. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  5925. }
  5926. for (auto& ifaceInstPair : interfaceMap)
  5927. {
  5928. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  5929. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  5930. if (slotNum >= 0)
  5931. {
  5932. BfIRValue vtablePtr;
  5933. int idx = interfaceEntry->mStartVirtualIdx;
  5934. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5935. if ((endVirtualIdx > ifaceMethodExtStart) && (ifaceMethodExtVar))
  5936. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  5937. else
  5938. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  5939. int slotVirtIdx = slotNum + vDataOfs;
  5940. if (vData[slotVirtIdx] == voidPtrNull)
  5941. {
  5942. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  5943. }
  5944. else
  5945. {
  5946. if (mCompiler->IsHotCompile())
  5947. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  5948. else
  5949. Fail("Interface slot collision error", typeDef->GetRefNode());
  5950. }
  5951. }
  5952. }
  5953. }
  5954. }
  5955. BfIRValue typeNameConst;
  5956. BfIRValue namespaceConst;
  5957. if (needsTypeNames)
  5958. {
  5959. typeNameConst = GetStringObjectValue(typeDef->mName->mString, !mIsComptimeModule);
  5960. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), !mIsComptimeModule);
  5961. }
  5962. else
  5963. {
  5964. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  5965. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5966. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5967. }
  5968. int baseTypeId = 0;
  5969. if (typeInstance->mBaseType != NULL)
  5970. {
  5971. baseTypeId = typeInstance->mBaseType->mTypeId;
  5972. }
  5973. BfTypeOptions* typeOptions = NULL;
  5974. if (typeInstance->mTypeOptionsIdx >= 0)
  5975. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5976. SizedArray<BfIRValue, 16> customAttrs;
  5977. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  5978. BfIRValue castedClassVData;
  5979. if (classVDataVar)
  5980. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  5981. else
  5982. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  5983. bool freflectIncludeTypeData = false;
  5984. bool reflectIncludeAllFields = false;
  5985. bool reflectIncludeAllMethods = false;
  5986. if (TypeIsSubTypeOf(typeInstance, attributeType))
  5987. {
  5988. reflectIncludeAllFields = true;
  5989. reflectIncludeAllMethods = true;
  5990. }
  5991. if (typeInstance->IsTuple())
  5992. {
  5993. // Required to generate tuple name at runtime
  5994. reflectIncludeAllFields = true;
  5995. }
  5996. BfReflectKind reflectKind = BfReflectKind_Type;
  5997. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  5998. {
  5999. BfReflectKind reflectKind = BfReflectKind_None;
  6000. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  6001. if (customAttrs != NULL)
  6002. {
  6003. for (auto& attr : customAttrs->mAttributes)
  6004. {
  6005. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  6006. }
  6007. delete customAttrs;
  6008. }
  6009. return reflectKind;
  6010. };
  6011. reflectKind = GetReflectKind(reflectKind, typeInstance);
  6012. // Fields
  6013. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  6014. BfIRValue emptyValueType = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  6015. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  6016. {
  6017. if (customAttributes == NULL)
  6018. return -1;
  6019. Array<BfCustomAttribute*> reflectAttributes;
  6020. for (auto& attr : customAttributes->mAttributes)
  6021. {
  6022. bool wantAttribute = false;
  6023. if (attr.mType->mCustomAttributes != NULL)
  6024. {
  6025. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  6026. if (usageAttribute != NULL)
  6027. {
  6028. // Check for Flags arg
  6029. if (usageAttribute->mCtorArgs.size() < 2)
  6030. continue;
  6031. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  6032. if (constant == NULL)
  6033. continue;
  6034. if (constant->mTypeCode == BfTypeCode_Boolean)
  6035. continue;
  6036. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  6037. wantAttribute = true;
  6038. }
  6039. }
  6040. if ((wantAttribute) && (attr.mType->mIsReified))
  6041. {
  6042. reflectAttributes.Add(&attr);
  6043. }
  6044. }
  6045. if (reflectAttributes.size() == 0)
  6046. return -1;
  6047. #define PUSH_INT8(val) data.push_back((uint8)val)
  6048. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  6049. #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); }
  6050. SizedArray<uint8, 16> data;
  6051. int customAttrIdx = (int)customAttrs.size();
  6052. data.push_back((uint8)reflectAttributes.size());
  6053. for (auto attr : reflectAttributes)
  6054. {
  6055. // Size prefix
  6056. int sizeIdx = (int)data.size();
  6057. PUSH_INT16(0); // mSize
  6058. PUSH_INT32(attr->mType->mTypeId); // mType
  6059. int ctorIdx = -1;
  6060. int ctorCount = 0;
  6061. attr->mType->mTypeDef->PopulateMemberSets();
  6062. BfMemberSetEntry* entry;
  6063. if (attr->mType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  6064. {
  6065. BfMethodDef* nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6066. while (nextMethodDef != NULL)
  6067. {
  6068. if (nextMethodDef == attr->mCtor)
  6069. ctorIdx = ctorCount;
  6070. nextMethodDef = nextMethodDef->mNextWithSameName;
  6071. ctorCount++;
  6072. }
  6073. }
  6074. BF_ASSERT(ctorIdx != -1);
  6075. if (ctorIdx != -1)
  6076. ctorIdx = (ctorCount - 1) - ctorIdx;
  6077. PUSH_INT16(ctorIdx);
  6078. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  6079. int argIdx = 0;
  6080. for (auto arg : attr->mCtorArgs)
  6081. {
  6082. auto argType = ctorMethodInstance->GetParamType(argIdx);
  6083. EncodeAttributeData(typeInstance, argType, arg, data, ctx.mUsedStringIdMap);
  6084. argIdx++;
  6085. }
  6086. int size = (int)data.size() - sizeIdx;
  6087. *((uint16*)&data[sizeIdx]) = size;
  6088. }
  6089. #undef PUSH_INT8
  6090. #undef PUSH_INT16
  6091. #undef PUSH_INT32
  6092. SizedArray<BfIRValue, 16> dataValues;
  6093. for (uint8 val : data)
  6094. dataValues.push_back(GetConstValue8(val));
  6095. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  6096. auto customAttrConst = mBfIRBuilder->CreateConstAgg_Value(dataArrayType, dataValues);
  6097. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  6098. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  6099. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  6100. customAttrs.push_back(customAttrArrayPtr);
  6101. return customAttrIdx;
  6102. };
  6103. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  6104. SizedArray<int, 16> reflectFieldIndices;
  6105. for (int pass = 0; pass < 2; pass++)
  6106. {
  6107. bool skippedField = false;
  6108. reflectFieldIndices.clear();
  6109. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  6110. {
  6111. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6112. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  6113. if (fieldDef == NULL)
  6114. continue;
  6115. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6116. bool includeField = reflectIncludeAllFields;
  6117. if (fieldInstance->mCustomAttributes != NULL)
  6118. {
  6119. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  6120. {
  6121. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6122. {
  6123. includeField = true;
  6124. }
  6125. else
  6126. {
  6127. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6128. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  6129. }
  6130. }
  6131. }
  6132. if ((fieldReflectKind & BfReflectKind_User) != 0)
  6133. includeField = true;
  6134. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  6135. includeField = true;
  6136. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  6137. includeField = true;
  6138. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  6139. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  6140. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  6141. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  6142. includeField |= forceReflectFields;
  6143. if (!includeField)
  6144. {
  6145. skippedField = true;
  6146. continue;
  6147. }
  6148. reflectFieldIndices.Add(fieldIdx);
  6149. }
  6150. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  6151. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  6152. // possible because we write out a SplatData structure containing just TypeIds in that case
  6153. if (pass == 0)
  6154. {
  6155. if (!typeInstance->IsSplattable())
  6156. break;
  6157. if (!skippedField)
  6158. break;
  6159. if (reflectFieldIndices.size() == 0)
  6160. break;
  6161. }
  6162. }
  6163. SizedArray<BfIRValue, 16> fieldTypes;
  6164. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  6165. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  6166. {
  6167. BfType* payloadType = typeInstance->GetUnionInnerType();
  6168. if (!payloadType->IsValuelessType())
  6169. {
  6170. BfIRValue payloadNameConst = GetStringObjectValue("$payload", !mIsComptimeModule);
  6171. SizedArray<BfIRValue, 8> payloadFieldVals;
  6172. if (is32Bit)
  6173. {
  6174. payloadFieldVals =
  6175. {
  6176. emptyValueType,
  6177. payloadNameConst, // mName
  6178. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6179. GetConstValue(0, intPtrType), // mData
  6180. GetConstValue(0, intPtrType), // mDataHi
  6181. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6182. GetConstValue(-1, intType), // mCustomAttributesIdx
  6183. };
  6184. }
  6185. else
  6186. {
  6187. payloadFieldVals =
  6188. {
  6189. emptyValueType,
  6190. payloadNameConst, // mName
  6191. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6192. GetConstValue(0, intPtrType), // mData
  6193. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6194. GetConstValue(-1, intType), // mCustomAttributesIdx
  6195. };
  6196. }
  6197. FixConstValueParams(reflectFieldDataType->ToTypeInstance(), payloadFieldVals);
  6198. auto payloadFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  6199. fieldTypes.push_back(payloadFieldData);
  6200. }
  6201. BfType* dscrType = typeInstance->GetDiscriminatorType();
  6202. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", !mIsComptimeModule);
  6203. SizedArray<BfIRValue, 8> dscrFieldVals;
  6204. if (is32Bit)
  6205. {
  6206. dscrFieldVals =
  6207. {
  6208. emptyValueType,
  6209. dscrNameConst, // mName
  6210. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6211. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6212. GetConstValue(0, intPtrType), // mDataHi
  6213. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6214. GetConstValue(-1, intType), // mCustomAttributesIdx
  6215. };
  6216. }
  6217. else
  6218. {
  6219. dscrFieldVals =
  6220. {
  6221. emptyValueType,
  6222. dscrNameConst, // mName
  6223. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6224. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6225. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6226. GetConstValue(-1, intType), // mCustomAttributesIdx
  6227. };
  6228. }
  6229. auto dscrFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  6230. fieldTypes.push_back(dscrFieldData);
  6231. }
  6232. for (auto fieldIdx : reflectFieldIndices)
  6233. {
  6234. if (!needsTypeData)
  6235. break;
  6236. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6237. fieldTypes.push_back(CreateFieldData(fieldInstance, _HandleCustomAttrs(fieldInstance->mCustomAttributes)));
  6238. }
  6239. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  6240. BfIRValue fieldDataPtr;
  6241. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  6242. if (fieldTypes.size() == 0)
  6243. {
  6244. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  6245. {
  6246. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  6247. SizedArray<BfIRValue, 3> splatTypes;
  6248. SizedArray<BfIRValue, 3> splatOffsets;
  6249. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  6250. {
  6251. auto checkTypeInstance = checkType->ToTypeInstance();
  6252. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  6253. PopulateType(checkTypeInstance);
  6254. if (checkType->IsStruct())
  6255. {
  6256. int dataEnd = offset;
  6257. if (checkTypeInstance->mBaseType != NULL)
  6258. _CheckSplat(checkTypeInstance->mBaseType, offset);
  6259. if (checkTypeInstance->mIsUnion)
  6260. {
  6261. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  6262. _CheckSplat(unionInnerType, offset);
  6263. }
  6264. else
  6265. {
  6266. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  6267. {
  6268. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  6269. if (fieldInstance->mDataIdx >= 0)
  6270. {
  6271. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  6272. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  6273. }
  6274. }
  6275. }
  6276. if (checkTypeInstance->IsEnum())
  6277. {
  6278. // Add discriminator
  6279. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  6280. if (checkTypeInstance->mPacking > 0)
  6281. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  6282. _CheckSplat(dscrType, dataEnd);
  6283. }
  6284. }
  6285. else if (checkType->IsMethodRef())
  6286. {
  6287. // auto methodRefType = (BfMethodRefType*)checkType;
  6288. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6289. // {
  6290. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6291. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  6292. // else
  6293. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  6294. // }
  6295. }
  6296. else if (!checkType->IsValuelessType())
  6297. {
  6298. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  6299. splatOffsets.Add(GetConstValue(offset, intType));
  6300. }
  6301. };
  6302. _CheckSplat(type, 0);
  6303. while (splatTypes.size() < 3)
  6304. {
  6305. splatTypes.Add(GetConstValue(0, typeIdType));
  6306. splatOffsets.Add(GetConstValue(0, intType));
  6307. }
  6308. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  6309. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  6310. SizedArray<BfIRValue, 8> splatVals =
  6311. {
  6312. emptyValueType,
  6313. splatTypesConst,
  6314. splatOffsetsConst
  6315. };
  6316. auto fieldSplatData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  6317. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  6318. fieldSplatData, typeDataName + ".splats");
  6319. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6320. }
  6321. else
  6322. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  6323. }
  6324. else
  6325. {
  6326. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  6327. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstAgg_Value(fieldDataConstType, fieldTypes);
  6328. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  6329. fieldDataConst, "fields." + typeDataName);
  6330. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6331. }
  6332. /// Methods
  6333. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  6334. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  6335. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  6336. struct _SortedMethodInfo
  6337. {
  6338. BfMethodDef* mMethodDef;
  6339. BfMethodCustomAttributes* mMethodCustomAttributes;
  6340. };
  6341. Array<_SortedMethodInfo> sortedMethodList;
  6342. SizedArray<BfIRValue, 16> methodTypes;
  6343. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  6344. {
  6345. if (!needsTypeData)
  6346. break;
  6347. // Disable const method reflection info for now
  6348. if (mIsComptimeModule)
  6349. break;
  6350. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6351. if (!methodInstanceGroup->IsImplemented())
  6352. continue;
  6353. auto methodDef = typeDef->mMethods[methodIdx];
  6354. if (methodDef->mIsNoReflect)
  6355. continue;
  6356. if (methodDef->mHasComptime)
  6357. continue;
  6358. auto defaultMethod = methodInstanceGroup->mDefault;
  6359. if (defaultMethod == NULL)
  6360. continue;
  6361. if (defaultMethod->mIsUnspecialized)
  6362. continue;
  6363. if (!defaultMethod->mIsReified)
  6364. continue;
  6365. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  6366. continue;
  6367. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  6368. continue;
  6369. if (!defaultMethod->mMethodDef->CanReflect())
  6370. continue;
  6371. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6372. bool includeMethod = reflectIncludeAllMethods;
  6373. if (typeInstance->IsDelegateOrFunction())
  6374. includeMethod = true;
  6375. BfMethodCustomAttributes* methodCustomAttributes = NULL;
  6376. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  6377. {
  6378. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes;
  6379. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  6380. {
  6381. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6382. {
  6383. includeMethod = true;
  6384. }
  6385. else
  6386. {
  6387. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6388. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  6389. }
  6390. }
  6391. }
  6392. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject)))
  6393. continue;
  6394. //
  6395. {
  6396. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  6397. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  6398. {
  6399. BfTypeState typeState;
  6400. typeState.mPrevState = mContext->mCurTypeState;
  6401. typeState.mForceActiveTypeDef = methodDef->mDeclaringType;
  6402. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  6403. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  6404. {
  6405. if (paramDecl->mAttributes != NULL)
  6406. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  6407. }
  6408. }
  6409. }
  6410. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  6411. includeMethod = true;
  6412. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  6413. includeMethod = true;
  6414. if ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend))
  6415. {
  6416. if ((methodReflectKind & BfReflectKind_Constructors) != 0)
  6417. includeMethod = true;
  6418. if ((methodDef->IsDefaultCtor()) && ((methodReflectKind & BfReflectKind_DefaultConstructor) != 0))
  6419. includeMethod = true;
  6420. }
  6421. if ((!includeMethod) && (typeOptions != NULL))
  6422. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  6423. if (!includeMethod)
  6424. continue;
  6425. sortedMethodList.Add({ methodDef, methodCustomAttributes });
  6426. }
  6427. auto _GetMethodKind = [](BfMethodDef* methodDef)
  6428. {
  6429. if (methodDef->mMethodType == BfMethodType_Ctor)
  6430. return 0;
  6431. return 1;
  6432. };
  6433. std::sort(sortedMethodList.begin(), sortedMethodList.end(), [_GetMethodKind](const _SortedMethodInfo& lhs, const _SortedMethodInfo& rhs)
  6434. {
  6435. int lhsKind = _GetMethodKind(lhs.mMethodDef);
  6436. int rhsKind = _GetMethodKind(rhs.mMethodDef);
  6437. if (lhsKind != rhsKind)
  6438. return lhsKind < rhsKind;
  6439. if (lhs.mMethodDef->mName != rhs.mMethodDef->mName)
  6440. return lhs.mMethodDef->mName < rhs.mMethodDef->mName;
  6441. return lhs.mMethodDef->mIdx < rhs.mMethodDef->mIdx;
  6442. });
  6443. for (auto& methodInfo : sortedMethodList)
  6444. {
  6445. auto methodDef = methodInfo.mMethodDef;
  6446. int methodIdx = methodDef->mIdx;
  6447. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6448. auto defaultMethod = methodInstanceGroup->mDefault;
  6449. BfModuleMethodInstance moduleMethodInstance;
  6450. BfIRValue funcVal = voidPtrNull;
  6451. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  6452. (!typeInstance->IsUnspecializedType()) &&
  6453. (methodDef->mMethodType != BfMethodType_Ignore) &&
  6454. (methodDef->mMethodType != BfMethodType_Mixin) &&
  6455. (!methodDef->mIsAbstract) &&
  6456. (methodDef->mGenericParams.size() == 0))
  6457. {
  6458. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6459. if (moduleMethodInstance.mFunc)
  6460. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6461. }
  6462. BfIRValue methodNameConst = GetStringObjectValue(methodDef->GetReflectName(), !mIsComptimeModule);
  6463. BfMethodFlags methodFlags = defaultMethod->GetMethodFlags();
  6464. int customAttrIdx = -1;
  6465. int returnCustomAttrIdx = -1;
  6466. if (methodInfo.mMethodCustomAttributes != NULL)
  6467. {
  6468. customAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mCustomAttributes);
  6469. returnCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mReturnCustomAttributes);
  6470. }
  6471. enum ParamFlags
  6472. {
  6473. ParamFlag_None = 0,
  6474. ParamFlag_Splat = 1,
  6475. ParamFlag_Implicit = 2,
  6476. ParamFlag_AppendIdx = 4,
  6477. ParamFlag_Params = 8
  6478. };
  6479. SizedArray<BfIRValue, 8> paramVals;
  6480. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  6481. {
  6482. String paramName = defaultMethod->GetParamName(paramIdx);
  6483. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  6484. ParamFlags paramFlags = ParamFlag_None;
  6485. if (defaultMethod->GetParamIsSplat(paramIdx))
  6486. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  6487. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  6488. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Implicit | ParamFlag_AppendIdx);
  6489. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_Params)
  6490. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Params);
  6491. BfIRValue paramNameConst = GetStringObjectValue(paramName, !mIsComptimeModule);
  6492. int paramCustomAttrIdx = -1;
  6493. if ((methodInfo.mMethodCustomAttributes != NULL) && (paramIdx < (int)methodInfo.mMethodCustomAttributes->mParamCustomAttributes.mSize))
  6494. paramCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mParamCustomAttributes[paramIdx]);
  6495. SizedArray<BfIRValue, 8> paramDataVals =
  6496. {
  6497. emptyValueType,
  6498. paramNameConst,
  6499. GetConstValue(paramType->mTypeId, typeIdType),
  6500. GetConstValue((int32)paramFlags, shortType),
  6501. GetConstValue(-1, intType), // defaultIdx
  6502. GetConstValue(paramCustomAttrIdx, intType) // customAttrIdx
  6503. };
  6504. auto paramData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  6505. paramVals.Add(paramData);
  6506. }
  6507. BfIRValue paramsVal;
  6508. if (paramVals.size() > 0)
  6509. {
  6510. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  6511. BfIRValue paramDataConst = mBfIRBuilder->CreateConstAgg_Value(paramDataArrayType, paramVals);
  6512. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  6513. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  6514. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  6515. }
  6516. else
  6517. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  6518. int vDataVal = -1;
  6519. if (defaultMethod->mVirtualTableIdx != -1)
  6520. {
  6521. int vDataIdx = -1;
  6522. if (type->IsInterface())
  6523. {
  6524. vDataIdx = defaultMethod->mVirtualTableIdx;
  6525. }
  6526. else
  6527. {
  6528. vDataIdx = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  6529. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  6530. {
  6531. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  6532. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6533. if (extMethodIdx >= 0)
  6534. {
  6535. // Extension?
  6536. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6537. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  6538. }
  6539. else
  6540. {
  6541. // Map this new virtual index back to the original index
  6542. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  6543. }
  6544. }
  6545. else
  6546. {
  6547. vDataIdx += defaultMethod->mVirtualTableIdx;
  6548. }
  6549. }
  6550. if (vDataVal == -1)
  6551. vDataVal = vDataIdx * mSystem->mPtrSize;
  6552. }
  6553. SizedArray<BfIRValue, 8> methodDataVals =
  6554. {
  6555. emptyValueType,
  6556. methodNameConst, // mName
  6557. funcVal, // mFuncPtr
  6558. paramsVal,
  6559. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  6560. GetConstValue((int)paramVals.size(), shortType),
  6561. GetConstValue(methodFlags, shortType),
  6562. GetConstValue(methodIdx, intType),
  6563. GetConstValue(vDataVal, intType),
  6564. GetConstValue(customAttrIdx, intType),
  6565. GetConstValue(returnCustomAttrIdx, intType),
  6566. };
  6567. auto methodData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  6568. methodTypes.push_back(methodData);
  6569. }
  6570. BfIRValue methodDataPtr;
  6571. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  6572. if (methodTypes.size() == 0)
  6573. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  6574. else
  6575. {
  6576. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  6577. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methodTypes);
  6578. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6579. methodDataConst, "methods." + typeDataName);
  6580. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  6581. }
  6582. /////
  6583. int interfaceCount = 0;
  6584. BfIRValue interfaceDataPtr;
  6585. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  6586. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  6587. Array<bool> wantsIfaceMethod;
  6588. bool wantsIfaceMethods = false;
  6589. if ((typeInstance->mInterfaces.IsEmpty()) || (!needsTypeData))
  6590. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  6591. else
  6592. {
  6593. SizedArray<BfIRValue, 16> interfaces;
  6594. for (auto& interface : typeInstance->mInterfaces)
  6595. {
  6596. SizedArray<BfIRValue, 8> interfaceDataVals =
  6597. {
  6598. emptyValueType,
  6599. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  6600. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  6601. GetConstValue(interface.mStartVirtualIdx, intType),
  6602. };
  6603. auto interfaceData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  6604. interfaces.push_back(interfaceData);
  6605. if (!mIsComptimeModule)
  6606. {
  6607. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6608. {
  6609. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  6610. if (ifaceMethodGroup->mExplicitlyReflected)
  6611. {
  6612. wantsIfaceMethods = true;
  6613. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  6614. while (tableIdx >= wantsIfaceMethod.size())
  6615. wantsIfaceMethod.Add(false);
  6616. wantsIfaceMethod[tableIdx] = true;
  6617. }
  6618. }
  6619. }
  6620. }
  6621. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  6622. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstAgg_Value(interfaceDataArrayType, interfaces);
  6623. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  6624. interfaceDataConst, "interfaces." + typeDataName);
  6625. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  6626. interfaceCount = (int)interfaces.size();
  6627. }
  6628. BfIRValue interfaceMethodTable;
  6629. int ifaceMethodTableSize = 0;
  6630. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  6631. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  6632. {
  6633. SizedArray<BfIRValue, 16> methods;
  6634. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  6635. {
  6636. BfIRValue funcVal = voidPtrNull;
  6637. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  6638. {
  6639. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  6640. if (!methodEntry.mMethodRef.IsNull())
  6641. {
  6642. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  6643. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  6644. (!methodInstance->mMethodDef->mIsAbstract))
  6645. {
  6646. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  6647. if (moduleMethodInstance.mFunc)
  6648. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6649. }
  6650. }
  6651. }
  6652. methods.Add(funcVal);
  6653. }
  6654. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  6655. methods.pop_back();
  6656. if (!methods.IsEmpty())
  6657. {
  6658. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  6659. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methods);
  6660. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6661. methodDataConst, "imethods." + typeDataName);
  6662. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  6663. ifaceMethodTableSize = (int)methods.size();
  6664. }
  6665. }
  6666. if (!interfaceMethodTable)
  6667. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6668. /////
  6669. int underlyingType = 0;
  6670. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  6671. {
  6672. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  6673. }
  6674. int outerTypeId = 0;
  6675. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  6676. if (outerType != NULL)
  6677. {
  6678. outerTypeId = outerType->mTypeId;
  6679. }
  6680. //
  6681. BfIRValue customAttrDataPtr;
  6682. if (customAttrs.size() > 0)
  6683. {
  6684. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  6685. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstAgg_Value(customAttrsArrayType, customAttrs);
  6686. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  6687. customAttrsConst, "customAttrs." + typeDataName);
  6688. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  6689. }
  6690. else
  6691. {
  6692. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6693. }
  6694. SizedArray<BfIRValue, 32> typeDataVals =
  6695. {
  6696. typeData,
  6697. castedClassVData, // mTypeClassVData
  6698. typeNameConst, // mName
  6699. namespaceConst, // mNamespace
  6700. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  6701. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  6702. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  6703. GetConstValue(baseTypeId, typeIdType), // mBaseType
  6704. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  6705. GetConstValue(outerTypeId, typeIdType), // mOuterType
  6706. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  6707. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  6708. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  6709. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  6710. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  6711. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  6712. GetConstValue(0, shortType), // mPropertyDataCount
  6713. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  6714. interfaceDataPtr, // mInterfaceDataPtr
  6715. interfaceMethodTable, // mInterfaceMethodTable
  6716. methodDataPtr, // mMethodDataPtr
  6717. voidPtrNull, // mPropertyDataPtr
  6718. fieldDataPtr, // mFieldDataPtr
  6719. customAttrDataPtr, // mCustomAttrDataPtr
  6720. };
  6721. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  6722. FixConstValueParams(typeInstanceType->ToTypeInstance(), typeDataVals);
  6723. auto typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, typeDataVals);
  6724. if (!needsTypeData)
  6725. {
  6726. // No need for anything beyond typeInstanceData
  6727. }
  6728. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  6729. {
  6730. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6731. SizedArray<BfIRValue, 4> unspecializedData =
  6732. {
  6733. typeInstanceData,
  6734. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  6735. };
  6736. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  6737. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6738. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, unspecializedData);
  6739. }
  6740. else if (typeInstance->IsGenericTypeInstance())
  6741. {
  6742. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6743. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  6744. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef->GetDefinition());
  6745. SizedArray<BfIRValue, 4> resolvedTypes;
  6746. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  6747. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  6748. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  6749. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  6750. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  6751. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstAgg_Value(genericArrayType, resolvedTypes);
  6752. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  6753. resolvedTypesConst, "resolvedTypes." + typeDataName);
  6754. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  6755. SizedArray<BfIRValue, 3> specGenericData =
  6756. {
  6757. typeInstanceData,
  6758. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  6759. resovledTypesPtr, // mFieldDataPtr
  6760. };
  6761. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6762. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, specGenericData);
  6763. if (typeInstance->IsArray())
  6764. {
  6765. auto arrayType = (BfArrayType*)typeInstance;
  6766. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  6767. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  6768. SizedArray<BfIRValue, 4> arrayData =
  6769. {
  6770. typeInstanceData,
  6771. GetConstValue(elementType->mSize, intType), // mElementSize
  6772. GetConstValue(1, byteType), // mRank
  6773. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  6774. };
  6775. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  6776. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  6777. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, arrayData);
  6778. }
  6779. }
  6780. BfIRValue typeDataVar;
  6781. if (needsTypeData)
  6782. {
  6783. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  6784. BfIRLinkageType_External, typeInstanceData, typeDataName);
  6785. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  6786. if (mBfIRBuilder->DbgHasInfo())
  6787. {
  6788. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  6789. }
  6790. }
  6791. else
  6792. {
  6793. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  6794. }
  6795. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  6796. mTypeDataRefs[typeInstance] = typeDataVar;
  6797. if ((!mIsComptimeModule) && (classVDataVar))
  6798. {
  6799. BF_ASSERT(!classVDataName.IsEmpty());
  6800. //vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  6801. int unboxedTypeId = type->mTypeId;
  6802. if (type->IsBoxed())
  6803. unboxedTypeId = type->GetUnderlyingType()->mTypeId;
  6804. if (mSystem->mPtrSize == 4)
  6805. {
  6806. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(type->mTypeId, intPtrType), voidPtrIRType);
  6807. vData[1] = mBfIRBuilder->CreateIntToPtr(GetConstValue(unboxedTypeId, intPtrType), voidPtrIRType);
  6808. }
  6809. else
  6810. {
  6811. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(((int64)unboxedTypeId << 32) | type->mTypeId, intPtrType), voidPtrIRType);
  6812. }
  6813. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  6814. auto classVDataConstData = mBfIRBuilder->CreateConstAgg_Value(classVDataConstDataType, vData);
  6815. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  6816. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6817. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  6818. else
  6819. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  6820. if (mBfIRBuilder->DbgHasInfo())
  6821. {
  6822. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6823. BfType* voidPtrType = CreatePointerType(voidType);
  6824. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6825. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  6826. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  6827. }
  6828. }
  6829. return typeDataVar;
  6830. }
  6831. BfIRValue BfModule::FixClassVData(BfIRValue value)
  6832. {
  6833. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  6834. return value;
  6835. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  6836. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  6837. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  6838. }
  6839. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  6840. {
  6841. // Note: this is not just for perf, it fixes a field var-type resolution issue
  6842. if (mBfIRBuilder->mIgnoreWrites)
  6843. return;
  6844. if (mIsComptimeModule)
  6845. return;
  6846. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  6847. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  6848. // When we access classes with static constructors FROM a static constructor,
  6849. // we call that other class's static constructor first. Recursion cannot occur, since
  6850. // we simply ignore subsequent attempts to re-enter the constructor
  6851. if (!typeInstance->mHasStaticInitMethod)
  6852. return;
  6853. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  6854. return;
  6855. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  6856. return;
  6857. auto checkTypeDef = typeInstance->mTypeDef;
  6858. checkTypeDef->PopulateMemberSets();
  6859. BfMethodDef* nextMethodDef = NULL;
  6860. BfMemberSetEntry* entry;
  6861. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  6862. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6863. while (nextMethodDef != NULL)
  6864. {
  6865. auto checkMethod = nextMethodDef;
  6866. nextMethodDef = nextMethodDef->mNextWithSameName;
  6867. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  6868. if (methodModule)
  6869. {
  6870. auto methodInstance = methodModule.mMethodInstance;
  6871. if ((methodInstance != NULL) &&
  6872. (methodInstance->mMethodDef->mIsStatic) &&
  6873. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  6874. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  6875. {
  6876. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  6877. break;
  6878. }
  6879. }
  6880. }
  6881. }
  6882. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  6883. {
  6884. auto methodOwner = methodInstance->GetOwner();
  6885. auto methodDef = methodInstance->mMethodDef;
  6886. auto methodDeclaration = methodDef->GetMethodDeclaration();
  6887. if (!methodDef->mIsExtern)
  6888. return BfIRFunction();
  6889. if (methodInstance->GetCustomAttributes() == NULL)
  6890. return BfIRFunction();
  6891. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  6892. {
  6893. String typeName = TypeToString(customAttribute.mType);
  6894. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  6895. {
  6896. methodInstance->mIsIntrinsic = true;
  6897. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  6898. String error;
  6899. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  6900. {
  6901. int stringId = constant->mInt32;
  6902. auto entry = mContext->mStringObjectIdMap[stringId];
  6903. String intrinName = entry.mString;
  6904. // if (intrinName.StartsWith(":"))
  6905. // {
  6906. // SizedArray<BfIRType, 2> paramTypes;
  6907. // for (auto& param : methodInstance->mParams)
  6908. // paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6909. // return mBfIRBuilder->GetIntrinsic(intrinName.Substring(1), mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6910. // }
  6911. // else
  6912. {
  6913. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  6914. if (intrinId != -1)
  6915. {
  6916. if (intrinId == BfIRIntrinsic_Malloc)
  6917. {
  6918. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6919. }
  6920. else if (intrinId == BfIRIntrinsic_Free)
  6921. {
  6922. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  6923. }
  6924. SizedArray<BfIRType, 2> paramTypes;
  6925. for (auto& param : methodInstance->mParams)
  6926. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6927. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6928. }
  6929. else if (reportFailure)
  6930. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  6931. }
  6932. }
  6933. else if (reportFailure)
  6934. error = "Intrinsic name must be a constant string";
  6935. if (reportFailure)
  6936. {
  6937. Fail(error, customAttribute.mRef);
  6938. }
  6939. }
  6940. }
  6941. return BfIRFunction();
  6942. }
  6943. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  6944. {
  6945. if (mBfIRBuilder->mIgnoreWrites)
  6946. return mBfIRBuilder->GetFakeFunction();
  6947. if (!mBuiltInFuncs[(int)funcTypeId])
  6948. {
  6949. SizedArray<BfIRType, 4> paramTypes;
  6950. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  6951. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6952. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  6953. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6954. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  6955. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  6956. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  6957. BfIRFunctionType funcType;
  6958. BfIRFunction func;
  6959. switch (funcTypeId)
  6960. {
  6961. case BfBuiltInFuncType_PrintF:
  6962. paramTypes.Add(nullPtrType);
  6963. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  6964. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  6965. break;
  6966. case BfBuiltInFuncType_Malloc:
  6967. {
  6968. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6969. {
  6970. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  6971. }
  6972. else
  6973. {
  6974. String funcName = mCompiler->mOptions.mMallocLinkName;
  6975. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  6976. funcName = "malloc";
  6977. func = mBfIRBuilder->GetFunction(funcName);
  6978. if (!func)
  6979. {
  6980. paramTypes.clear();
  6981. paramTypes.push_back(intType);
  6982. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  6983. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6984. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  6985. }
  6986. }
  6987. }
  6988. break;
  6989. case BfBuiltInFuncType_Free:
  6990. {
  6991. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6992. {
  6993. func = GetInternalMethod("Dbg_RawFree").mFunc;
  6994. }
  6995. else
  6996. {
  6997. String funcName = mCompiler->mOptions.mFreeLinkName;
  6998. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  6999. funcName = "free";
  7000. func = mBfIRBuilder->GetFunction(funcName);
  7001. if (!func)
  7002. {
  7003. paramTypes.clear();
  7004. paramTypes.push_back(nullPtrType);
  7005. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  7006. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  7007. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  7008. }
  7009. }
  7010. }
  7011. break;
  7012. case BfBuiltInFuncType_LoadSharedLibraries:
  7013. paramTypes.clear();
  7014. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  7015. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  7016. break;
  7017. default: break;
  7018. }
  7019. mBuiltInFuncs[(int)funcTypeId] = func;
  7020. return func;
  7021. }
  7022. return mBuiltInFuncs[(int)funcTypeId];
  7023. }
  7024. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized, Array<BfTypeReference*>* deferredResolveTypes)
  7025. {
  7026. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  7027. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  7028. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  7029. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  7030. BfAutoComplete* bfAutocomplete = NULL;
  7031. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  7032. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  7033. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  7034. {
  7035. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  7036. {
  7037. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  7038. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  7039. {
  7040. String filter = nameNode->ToString();
  7041. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  7042. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  7043. if (nameIdx != 0)
  7044. {
  7045. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  7046. }
  7047. }
  7048. }
  7049. }
  7050. for (auto constraint : constraintDef->mConstraints)
  7051. {
  7052. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  7053. {
  7054. BfGenericOperatorConstraintInstance opConstraintInstance;
  7055. if (opConstraint->mLeftType != NULL)
  7056. {
  7057. if (bfAutocomplete != NULL)
  7058. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  7059. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces_All);
  7060. if (opConstraintInstance.mLeftType == NULL)
  7061. continue;
  7062. }
  7063. if (opConstraint->mRightType == NULL)
  7064. {
  7065. // We had a failure in parsing
  7066. continue;
  7067. }
  7068. if (opConstraint->mRightType != NULL)
  7069. {
  7070. if (bfAutocomplete != NULL)
  7071. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  7072. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces_All);
  7073. if (opConstraintInstance.mRightType == NULL)
  7074. continue;
  7075. }
  7076. if (opConstraint->mOpToken == NULL)
  7077. {
  7078. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  7079. continue;
  7080. }
  7081. if (opConstraint->mLeftType != NULL)
  7082. {
  7083. if (opConstraint->mRightType == NULL)
  7084. {
  7085. // Parse should have failed
  7086. continue;
  7087. }
  7088. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  7089. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  7090. {
  7091. Fail("Invalid binary operator", opConstraint->mOpToken);
  7092. continue;
  7093. }
  7094. }
  7095. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  7096. {
  7097. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  7098. }
  7099. else
  7100. {
  7101. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  7102. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  7103. {
  7104. Fail("Invalid unary operator", opConstraint->mOpToken);
  7105. continue;
  7106. }
  7107. }
  7108. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  7109. continue;
  7110. }
  7111. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  7112. if (bfAutocomplete != NULL)
  7113. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  7114. //TODO: Constraints may refer to other generic params (of either type or method)
  7115. // TO allow resolution, perhaps move this generic param initialization into GetMethodInstance (passing a genericPass bool)
  7116. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_AllowGenericMethodParamConstValue;
  7117. if (isUnspecialized)
  7118. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_DisallowComptime);
  7119. // We we have a deferredResolveTypes then we defer the generic validation, because we may have a case like
  7120. // `where T : Dictionay<TElem, int> and TElem : IHashable` and we don't want to throw the error on `T` before we build `TElem`
  7121. BfType* constraintType;
  7122. if (constraintTypeRef->IsA<BfVarTypeReference>())
  7123. constraintType = GetPrimitiveType(BfTypeCode_Var);
  7124. else
  7125. constraintType = ResolveTypeRef(constraintTypeRef, (deferredResolveTypes != NULL) ? BfPopulateType_Identity : BfPopulateType_Declaration, resolveFlags);
  7126. if (constraintType != NULL)
  7127. {
  7128. if (deferredResolveTypes != NULL)
  7129. {
  7130. PopulateType(constraintType, BfPopulateType_Declaration);
  7131. if (constraintType->IsUnspecializedTypeVariation())
  7132. deferredResolveTypes->Add(constraintTypeRef);
  7133. }
  7134. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7135. {
  7136. bool isValidTypeCode = false;
  7137. BfTypeCode typeCode = BfTypeCode_None;
  7138. if (constraintType->IsTypedPrimitive())
  7139. {
  7140. auto underlyingType = constraintType->GetUnderlyingType();
  7141. if (underlyingType->IsPrimitiveType())
  7142. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  7143. }
  7144. if (constraintType->IsPrimitiveType())
  7145. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  7146. if (constraintType->IsInstanceOf(mCompiler->mStringTypeDef))
  7147. isValidTypeCode = true;
  7148. if (constraintType->IsValueType())
  7149. isValidTypeCode = true;
  7150. if (constraintType->IsVar())
  7151. isValidTypeCode = true;
  7152. switch (typeCode)
  7153. {
  7154. case BfTypeCode_StringId:
  7155. case BfTypeCode_Boolean:
  7156. case BfTypeCode_Int8:
  7157. case BfTypeCode_UInt8:
  7158. case BfTypeCode_Int16:
  7159. case BfTypeCode_UInt16:
  7160. case BfTypeCode_Int32:
  7161. case BfTypeCode_UInt32:
  7162. case BfTypeCode_Int64:
  7163. case BfTypeCode_UInt64:
  7164. case BfTypeCode_IntPtr:
  7165. case BfTypeCode_UIntPtr:
  7166. case BfTypeCode_IntUnknown:
  7167. case BfTypeCode_UIntUnknown:
  7168. case BfTypeCode_Float:
  7169. case BfTypeCode_Double:
  7170. case BfTypeCode_Char8:
  7171. case BfTypeCode_Char16:
  7172. case BfTypeCode_Char32:
  7173. isValidTypeCode = true;
  7174. break;
  7175. default: break;
  7176. }
  7177. if (isValidTypeCode)
  7178. {
  7179. genericParamInstance->mTypeConstraint = constraintType;
  7180. }
  7181. else
  7182. {
  7183. Fail("Const constraint must be a valuetype or string", constraintTypeRef);
  7184. }
  7185. }
  7186. else
  7187. {
  7188. bool checkEquality = false;
  7189. if (constraintType->IsVar())
  7190. {
  7191. // From a `comptype` generic undef resolution. Ignore.
  7192. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_ComptypeExpr);
  7193. genericParamInstance->mComptypeConstraint.Add(constraintTypeRef);
  7194. continue;
  7195. }
  7196. else if (constraintType->IsPrimitiveType())
  7197. {
  7198. checkEquality = true;
  7199. }
  7200. if (constraintType->IsArray())
  7201. {
  7202. if (isUnspecialized)
  7203. {
  7204. 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);
  7205. continue;
  7206. }
  7207. checkEquality = true;
  7208. }
  7209. if (constraintType->IsGenericParam())
  7210. {
  7211. checkEquality = true;
  7212. }
  7213. else if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  7214. {
  7215. checkEquality = true;
  7216. }
  7217. if (checkEquality)
  7218. {
  7219. genericParamInstance->mTypeConstraint = constraintType;
  7220. }
  7221. else if (constraintType->IsInterface())
  7222. {
  7223. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  7224. }
  7225. else
  7226. {
  7227. auto constraintTypeInst = constraintType->ToTypeInstance();
  7228. if (genericParamInstance->mTypeConstraint != NULL)
  7229. {
  7230. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  7231. {
  7232. // Allow more specific type
  7233. genericParamInstance->mTypeConstraint = constraintTypeInst;
  7234. }
  7235. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  7236. {
  7237. // Silently ignore less-specific type
  7238. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  7239. {
  7240. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  7241. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Class);
  7242. }
  7243. }
  7244. else
  7245. {
  7246. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  7247. return;
  7248. }
  7249. }
  7250. else
  7251. genericParamInstance->mTypeConstraint = constraintType;
  7252. }
  7253. }
  7254. }
  7255. }
  7256. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  7257. (genericParamInstance->mTypeConstraint == NULL))
  7258. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  7259. }
  7260. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  7261. {
  7262. if (genericParamSource.mMethodInstance != NULL)
  7263. {
  7264. //auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  7265. //SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  7266. return MethodToString(genericParamSource.mMethodInstance);
  7267. }
  7268. else
  7269. {
  7270. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  7271. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  7272. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  7273. return TypeToString(typeInst);
  7274. }
  7275. }
  7276. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  7277. {
  7278. Array<String> methodParamNameOverrides;
  7279. auto _TypeToString = [&](BfType* type)
  7280. {
  7281. if (genericParamSource.mMethodInstance != NULL)
  7282. {
  7283. if (methodParamNameOverrides.IsEmpty())
  7284. {
  7285. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  7286. methodParamNameOverrides.Add(genericParam->mName);
  7287. }
  7288. return TypeToString(type, &methodParamNameOverrides);
  7289. }
  7290. return TypeToString(type);
  7291. };
  7292. bool ignoreErrors = (errorOut == NULL) ||
  7293. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  7294. BfType* origCheckArgType = checkArgType;
  7295. if (origCheckArgType->IsRef())
  7296. origCheckArgType = origCheckArgType->GetUnderlyingType();
  7297. bool argIsReferenceType = false;
  7298. int checkGenericParamFlags = 0;
  7299. if (checkArgType->IsGenericParam())
  7300. {
  7301. BfGenericParamInstance* checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  7302. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  7303. if (checkGenericParamInst->mTypeConstraint != NULL)
  7304. checkArgType = checkGenericParamInst->mTypeConstraint;
  7305. if (checkGenericParamInst->mGenericParamFlags & BfGenericParamFlag_Var)
  7306. checkArgType = GetPrimitiveType(BfTypeCode_Var);
  7307. // if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  7308. // {
  7309. // argMayBeReferenceType = false;
  7310. // }
  7311. // else
  7312. // {
  7313. // argMayBeReferenceType = true;
  7314. // }
  7315. }
  7316. if (checkArgType->IsObjectOrInterface())
  7317. argIsReferenceType = true;
  7318. BfTypeInstance* typeConstraintInst = NULL;
  7319. if (genericParamInst->mTypeConstraint != NULL)
  7320. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  7321. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  7322. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  7323. {
  7324. if ((!ignoreErrors) && (PreFail()))
  7325. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  7326. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7327. return false;
  7328. }
  7329. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  7330. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  7331. {
  7332. if ((!ignoreErrors) && (PreFail()))
  7333. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  7334. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7335. return false;
  7336. }
  7337. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  7338. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argIsReferenceType))
  7339. {
  7340. if ((!ignoreErrors) && (PreFail()))
  7341. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  7342. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7343. return false;
  7344. }
  7345. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum)
  7346. {
  7347. bool isEnum = checkArgType->IsEnum();
  7348. if ((origCheckArgType->IsGenericParam()) && (checkArgType->IsInstanceOf(mCompiler->mEnumTypeDef)))
  7349. isEnum = true;
  7350. if (((checkGenericParamFlags & (BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!isEnum))
  7351. {
  7352. if ((!ignoreErrors) && (PreFail()))
  7353. *errorOut = Fail(StrFormat("The type '%s' must be an enum type in order to use it as parameter '%s' for '%s'",
  7354. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7355. return false;
  7356. }
  7357. }
  7358. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) &&
  7359. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (checkArgType->IsInterface()))
  7360. {
  7361. if ((!ignoreErrors) && (PreFail()))
  7362. *errorOut = Fail(StrFormat("The type '%s' must be an concrete type in order to use it as parameter '%s' for '%s'",
  7363. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7364. return false;
  7365. }
  7366. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Interface) &&
  7367. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsInterface()))
  7368. {
  7369. if ((!ignoreErrors) && (PreFail()))
  7370. *errorOut = Fail(StrFormat("The type '%s' must be an interface type in order to use it as parameter '%s' for '%s'",
  7371. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7372. return false;
  7373. }
  7374. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7375. {
  7376. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  7377. {
  7378. if ((!ignoreErrors) && (PreFail()))
  7379. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  7380. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7381. return false;
  7382. }
  7383. }
  7384. else
  7385. {
  7386. if (checkArgType->IsConstExprValue())
  7387. {
  7388. if ((!ignoreErrors) && (PreFail()))
  7389. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  7390. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7391. return false;
  7392. }
  7393. }
  7394. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  7395. {
  7396. bool canDelete = false;
  7397. if (checkArgType->IsPointer())
  7398. canDelete = true;
  7399. else if (checkArgType->IsObjectOrInterface())
  7400. canDelete = true;
  7401. else if ((checkGenericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var)) != 0)
  7402. canDelete = true;
  7403. if (!canDelete)
  7404. {
  7405. if ((!ignoreErrors) && (PreFail()))
  7406. {
  7407. if (checkArgType->IsGenericParam())
  7408. *errorOut = Fail(StrFormat("Must add 'where %s : delete' constraint in order to use type as parameter '%s' for '%s'",
  7409. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7410. else
  7411. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  7412. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7413. }
  7414. return false;
  7415. }
  7416. }
  7417. if (checkArgType->IsPointer())
  7418. {
  7419. auto ptrType = (BfPointerType*)checkArgType;
  7420. checkArgType = ptrType->mElementType;
  7421. }
  7422. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  7423. {
  7424. bool canAlloc = false;
  7425. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  7426. {
  7427. if (checkTypeInst->IsObjectOrStruct())
  7428. {
  7429. checkTypeInst->mTypeDef->PopulateMemberSets();
  7430. BfMemberSetEntry* entry = NULL;
  7431. BfMethodDef* checkMethodDef = NULL;
  7432. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  7433. if (entry != NULL)
  7434. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  7435. bool hadProtected = false;
  7436. while (checkMethodDef != NULL)
  7437. {
  7438. if (!checkMethodDef->mParams.IsEmpty())
  7439. {
  7440. auto firstParam = checkMethodDef->mParams[0];
  7441. if (((firstParam->mParamKind == BfParamKind_Params) || (firstParam->mParamKind == BfParamKind_AppendIdx) || (firstParam->mParamKind == BfParamKind_VarArgs)) ||
  7442. ((firstParam->mParamDeclaration != NULL) && (firstParam->mParamDeclaration->mInitializer != NULL)))
  7443. {
  7444. // Allow all-default params
  7445. }
  7446. else
  7447. {
  7448. checkMethodDef = checkMethodDef->mNextWithSameName;
  7449. continue;
  7450. }
  7451. }
  7452. if (checkMethodDef->mProtection == BfProtection_Public)
  7453. {
  7454. canAlloc = true;
  7455. break;
  7456. }
  7457. if ((checkMethodDef->mProtection == BfProtection_Protected) || (checkMethodDef->mProtection == BfProtection_ProtectedInternal))
  7458. hadProtected = true;
  7459. checkMethodDef = checkMethodDef->mNextWithSameName;
  7460. }
  7461. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  7462. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  7463. }
  7464. }
  7465. else if (checkArgType->IsGenericParam())
  7466. {
  7467. canAlloc = (checkGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) != 0;
  7468. }
  7469. else if (checkArgType->IsPrimitiveType())
  7470. {
  7471. // Any primitive types and stuff can be allocated
  7472. canAlloc = true;
  7473. }
  7474. if (!canAlloc)
  7475. {
  7476. if ((!ignoreErrors) && (PreFail()))
  7477. {
  7478. if (checkArgType->IsGenericParam())
  7479. *errorOut = Fail(StrFormat("Must add 'where %s : new' constraint in order to use type as parameter '%s' for '%s'",
  7480. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7481. else
  7482. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  7483. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7484. }
  7485. return false;
  7486. }
  7487. }
  7488. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  7489. return true;
  7490. if (genericParamInst->mTypeConstraint != NULL)
  7491. {
  7492. bool constraintMatched = false;
  7493. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7494. {
  7495. if (checkArgType->IsConstExprValue())
  7496. {
  7497. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  7498. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  7499. {
  7500. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  7501. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  7502. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  7503. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  7504. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  7505. (primType->mTypeDef->mTypeCode != BfTypeCode_Let) &&
  7506. (primType->mTypeDef->mTypeCode != BfTypeCode_Var))
  7507. {
  7508. bool doError = true;
  7509. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  7510. {
  7511. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7512. {
  7513. if (mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue))
  7514. doError = false;
  7515. }
  7516. }
  7517. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_Float) && ((constExprValueType->mValue.mTypeCode == BfTypeCode_Double)))
  7518. {
  7519. doError = false;
  7520. }
  7521. if (doError)
  7522. {
  7523. if ((!ignoreErrors) && (PreFail()))
  7524. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7525. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7526. return false;
  7527. }
  7528. }
  7529. }
  7530. else if (genericParamInst->mTypeConstraint != constExprValueType->mType)
  7531. {
  7532. if ((!ignoreErrors) && (PreFail()))
  7533. *errorOut = Fail(StrFormat("Const generic argument '%s', declared as '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7534. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7535. return false;
  7536. }
  7537. }
  7538. }
  7539. else
  7540. {
  7541. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  7542. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  7543. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7544. if (convCheckConstraint == NULL)
  7545. return false;
  7546. if ((checkArgType->IsMethodRef()) || (checkArgType->IsFunction()))
  7547. {
  7548. if (convCheckConstraint->IsDelegate())
  7549. {
  7550. BfMethodInstance* checkMethodInstance;
  7551. if (checkArgType->IsMethodRef())
  7552. {
  7553. auto methodRefType = (BfMethodRefType*)checkArgType;
  7554. checkMethodInstance = methodRefType->mMethodRef;
  7555. }
  7556. else
  7557. {
  7558. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  7559. }
  7560. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  7561. if (checkMethodInstance->HasExplicitThis() != 0)
  7562. {
  7563. // Don't allow functions with explicit 'this'
  7564. }
  7565. else
  7566. {
  7567. BfExprEvaluator exprEvaluator(this);
  7568. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  7569. constraintMatched = true;
  7570. }
  7571. }
  7572. else if (convCheckConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef))
  7573. constraintMatched = true;
  7574. else if ((checkArgType->IsFunction()) && (convCheckConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))
  7575. constraintMatched = true;
  7576. }
  7577. else if ((checkArgType == convCheckConstraint) || (checkArgType->IsVar()) || (TypeIsSubTypeOf(checkArgType->ToTypeInstance(), convCheckConstraint->ToTypeInstance())))
  7578. {
  7579. constraintMatched = true;
  7580. }
  7581. else if (origCheckArgType->IsWrappableType())
  7582. {
  7583. if (origCheckArgType->IsSizedArray())
  7584. {
  7585. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  7586. if (convCheckConstraint->IsGenericTypeInstance())
  7587. {
  7588. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  7589. if (convCheckConstraintInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  7590. {
  7591. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  7592. {
  7593. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  7594. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  7595. constraintMatched = true;
  7596. }
  7597. }
  7598. }
  7599. }
  7600. if (!constraintMatched)
  7601. {
  7602. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7603. if ((wrappedStructType == convCheckConstraint) || (TypeIsSubTypeOf(wrappedStructType, convCheckConstraint->ToTypeInstance())))
  7604. constraintMatched = true;
  7605. }
  7606. }
  7607. if (!constraintMatched)
  7608. {
  7609. if ((!ignoreErrors) && (PreFail()))
  7610. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  7611. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  7612. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  7613. return false;
  7614. }
  7615. }
  7616. }
  7617. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  7618. {
  7619. BfType* convCheckConstraint = checkConstraint;
  7620. if (convCheckConstraint->IsUnspecializedType())
  7621. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7622. if (convCheckConstraint == NULL)
  7623. return false;
  7624. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  7625. bool implementsInterface = false;
  7626. if (origCheckArgType != checkArgType)
  7627. {
  7628. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  7629. }
  7630. if (!implementsInterface)
  7631. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  7632. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  7633. {
  7634. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7635. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7636. implementsInterface = true;
  7637. }
  7638. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  7639. {
  7640. auto underlyingType = origCheckArgType->GetUnderlyingType();
  7641. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  7642. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7643. implementsInterface = true;
  7644. }
  7645. if (!implementsInterface)
  7646. {
  7647. if ((!ignoreErrors) && (PreFail()))
  7648. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  7649. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  7650. return false;
  7651. }
  7652. }
  7653. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  7654. {
  7655. auto leftType = checkOpConstraint.mLeftType;
  7656. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  7657. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs, mCurTypeInstance);
  7658. if (leftType != NULL)
  7659. leftType = FixIntUnknown(leftType);
  7660. auto rightType = checkOpConstraint.mRightType;
  7661. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  7662. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs, mCurTypeInstance);
  7663. if (rightType != NULL)
  7664. rightType = FixIntUnknown(rightType);
  7665. BfConstraintState constraintSet;
  7666. constraintSet.mPrevState = mContext->mCurConstraintState;
  7667. constraintSet.mGenericParamInstance = genericParamInst;
  7668. constraintSet.mLeftType = leftType;
  7669. constraintSet.mRightType = rightType;
  7670. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  7671. if (!CheckConstraintState(NULL))
  7672. return false;
  7673. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  7674. {
  7675. BfExprEvaluator exprEvaluator(this);
  7676. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  7677. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7678. //
  7679. {
  7680. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7681. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7682. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  7683. }
  7684. if ((!exprEvaluator.mResult) ||
  7685. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  7686. {
  7687. if ((!ignoreErrors) && (PreFail()))
  7688. {
  7689. if (genericParamInst->mExternType != NULL)
  7690. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  7691. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  7692. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7693. ), checkArgTypeRef);
  7694. else
  7695. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  7696. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7697. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7698. ), checkArgTypeRef);
  7699. }
  7700. return false;
  7701. }
  7702. }
  7703. else
  7704. {
  7705. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7706. StringT<128> failedOpName;
  7707. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  7708. {
  7709. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7710. failedOpName = "implicit conversion from '";
  7711. }
  7712. else
  7713. {
  7714. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7715. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7716. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  7717. {
  7718. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7719. failedOpName = "explicit conversion from '";
  7720. }
  7721. else
  7722. {
  7723. BfExprEvaluator exprEvaluator(this);
  7724. exprEvaluator.mResult = rightValue;
  7725. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  7726. if ((!exprEvaluator.mResult) ||
  7727. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  7728. {
  7729. failedOpName += "unary operation '";
  7730. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  7731. }
  7732. }
  7733. }
  7734. if (!failedOpName.IsEmpty())
  7735. {
  7736. if ((!ignoreErrors) && (PreFail()))
  7737. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  7738. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7739. failedOpName.c_str(), TypeToString(rightType).c_str()
  7740. ), checkArgTypeRef);
  7741. return false;
  7742. }
  7743. }
  7744. }
  7745. return true;
  7746. }
  7747. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  7748. {
  7749. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  7750. {
  7751. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  7752. return genericParamType;
  7753. }
  7754. auto genericParamType = new BfGenericParamType();
  7755. genericParamType->mContext = mContext;
  7756. genericParamType->mGenericParamKind = paramKind;
  7757. genericParamType->mGenericParamIdx = paramIdx;
  7758. PopulateType(genericParamType);
  7759. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  7760. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  7761. BfResolvedTypeSet::LookupContext lookupCtx;
  7762. lookupCtx.mModule = this;
  7763. BfResolvedTypeSet::EntryRef typeEntry;
  7764. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  7765. BF_ASSERT(inserted);
  7766. typeEntry->mValue = genericParamType;
  7767. return genericParamType;
  7768. }
  7769. static int sValueFromExprIdx = 0;
  7770. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  7771. {
  7772. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  7773. if ((result) && (!ignoreNullable))
  7774. {
  7775. if (result.mType->IsVar())
  7776. return result;
  7777. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  7778. //TODO: Make this work, needed for 'void' and such
  7779. BfType* nullableType = NULL;
  7780. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  7781. {
  7782. BfTypeVector typeVec;
  7783. typeVec.push_back(result.mType);
  7784. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  7785. BF_ASSERT(nullableType != NULL);
  7786. }
  7787. // Go back to start and do any setup we need
  7788. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7789. BfTypedValue nullableTypedValue;
  7790. if (nullableType != NULL)
  7791. {
  7792. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  7793. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  7794. GetConstValue(nullableType->mSize), nullableType->mAlign);
  7795. }
  7796. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7797. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  7798. mBfIRBuilder->SetInsertPoint(notNullBB);
  7799. result = LoadValue(result);
  7800. if (nullableTypedValue)
  7801. {
  7802. auto elementType = nullableType->GetUnderlyingType();
  7803. if (elementType->IsVar())
  7804. {
  7805. // Do nothing
  7806. }
  7807. else if (elementType->IsValuelessType())
  7808. {
  7809. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  7810. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  7811. }
  7812. else
  7813. {
  7814. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  7815. mBfIRBuilder->CreateAlignedStore(result.mValue, ptrValue, result.mType->mAlign);
  7816. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  7817. mBfIRBuilder->CreateAlignedStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue, 1);
  7818. }
  7819. result = nullableTypedValue;
  7820. }
  7821. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7822. AddBasicBlock(pendingNullCond->mDoneBB);
  7823. if (nullableType == NULL)
  7824. {
  7825. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  7826. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  7827. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  7828. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  7829. {
  7830. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  7831. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  7832. }
  7833. result.mValue = phi;
  7834. }
  7835. }
  7836. else
  7837. {
  7838. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7839. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7840. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7841. AddBasicBlock(pendingNullCond->mDoneBB);
  7842. }
  7843. delete mCurMethodState->mPendingNullConditional;
  7844. mCurMethodState->mPendingNullConditional = NULL;
  7845. return result;
  7846. }
  7847. BF_NOINLINE void BfModule::EvaluateWithNewConditionalScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  7848. {
  7849. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  7850. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData);
  7851. if (mCurMethodState != NULL)
  7852. {
  7853. deferredLocalAssignData.mIsIfCondition = true;
  7854. deferredLocalAssignData.mIfMayBeSkipped = true;
  7855. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  7856. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  7857. mCurMethodState->mDeferredLocalAssignData = &deferredLocalAssignData;
  7858. }
  7859. BfScopeData newScope;
  7860. newScope.mOuterIsConditional = true;
  7861. newScope.mAllowTargeting = false;
  7862. if (mCurMethodState != NULL)
  7863. {
  7864. mCurMethodState->AddScope(&newScope);
  7865. NewScopeState(true, false);
  7866. }
  7867. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7868. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  7869. if (mCurMethodState != NULL)
  7870. RestoreScopeState();
  7871. }
  7872. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7873. {
  7874. //
  7875. {
  7876. BP_ZONE("CreateValueFromExpression:CheckStack");
  7877. StackHelper stackHelper;
  7878. if (!stackHelper.CanStackExpand(128 * 1024))
  7879. {
  7880. BfTypedValue result;
  7881. if (!stackHelper.Execute([&]()
  7882. {
  7883. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7884. }))
  7885. {
  7886. Fail("Expression too complex to compile", expr);
  7887. }
  7888. return result;
  7889. }
  7890. }
  7891. BP_ZONE("BfModule::CreateValueFromExpression");
  7892. if (outOrigType != NULL)
  7893. *outOrigType = NULL;
  7894. exprEvaluator.mExpectingType = wantTypeRef;
  7895. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7896. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  7897. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  7898. {
  7899. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope->mScopeKind != BfScopeKind_StatementTarget_Conditional))
  7900. {
  7901. EvaluateWithNewConditionalScope(exprEvaluator, expr, flags);
  7902. }
  7903. else
  7904. {
  7905. SetAndRestoreValue<bool> prevIsConditional(mCurMethodState->mCurScope->mIsConditional, true);
  7906. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7907. }
  7908. }
  7909. else
  7910. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7911. if (!exprEvaluator.mResult)
  7912. {
  7913. if ((flags & BfEvalExprFlags_InferReturnType) != 0)
  7914. return exprEvaluator.mResult;
  7915. if (!mCompiler->mPassInstance->HasFailed())
  7916. {
  7917. if (PreFail())
  7918. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  7919. }
  7920. return BfTypedValue();
  7921. }
  7922. auto typedVal = exprEvaluator.mResult;
  7923. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  7924. {
  7925. BF_ASSERT(typedVal.mType->IsGenericParam());
  7926. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  7927. bool handled = false;
  7928. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7929. {
  7930. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  7931. if (genericTypeConstraint != NULL)
  7932. {
  7933. auto underlyingConstraint = genericTypeConstraint;
  7934. if ((underlyingConstraint != NULL) && (underlyingConstraint->IsBoxed()))
  7935. underlyingConstraint = underlyingConstraint->GetUnderlyingType();
  7936. if (underlyingConstraint != NULL)
  7937. {
  7938. BfTypedValue result;
  7939. result.mKind = BfTypedValueKind_Value;
  7940. result.mType = genericTypeConstraint;
  7941. result.mValue = mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(underlyingConstraint));
  7942. typedVal = result;
  7943. handled = true;
  7944. }
  7945. }
  7946. }
  7947. if (!handled)
  7948. {
  7949. //Fail("Only const generic parameters can be used as values", expr);
  7950. AssertErrorState();
  7951. return BfTypedValue();
  7952. }
  7953. }
  7954. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  7955. FixIntUnknown(typedVal);
  7956. if (!mBfIRBuilder->mIgnoreWrites)
  7957. FixValueActualization(typedVal);
  7958. exprEvaluator.CheckResultForReading(typedVal);
  7959. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  7960. {
  7961. if ((flags & BfEvalExprFlags_NoCast) == 0)
  7962. {
  7963. // Only allow a 'ref' type if we have an explicit 'ref' operator
  7964. bool allowRef = false;
  7965. BfAstNode* checkExpr = expr;
  7966. while (checkExpr != NULL)
  7967. {
  7968. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  7969. checkExpr = parenExpr->mExpression;
  7970. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  7971. {
  7972. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  7973. allowRef = true;
  7974. break;
  7975. }
  7976. if (auto block = BfNodeDynCast<BfBlock>(checkExpr))
  7977. {
  7978. if (block->mChildArr.mSize == 0)
  7979. break;
  7980. checkExpr = block->mChildArr.back();
  7981. }
  7982. else
  7983. break;
  7984. }
  7985. if (!allowRef)
  7986. typedVal = RemoveRef(typedVal);
  7987. }
  7988. }
  7989. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  7990. {
  7991. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsDataIncomplete()) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  7992. {
  7993. if (typedVal.mValue.IsFake())
  7994. {
  7995. InternalError("Unexpected fakeval in CreateValueFromExpression");
  7996. typedVal = GetDefaultTypedValue(typedVal.mType);
  7997. }
  7998. }
  7999. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8000. }
  8001. if (wantTypeRef != NULL)
  8002. {
  8003. if (outOrigType != NULL)
  8004. *outOrigType = typedVal.mType;
  8005. if (((flags & BfEvalExprFlags_NoCast) == 0) && (!wantTypeRef->IsVar()))
  8006. {
  8007. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  8008. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  8009. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  8010. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  8011. if (!typedVal)
  8012. return typedVal;
  8013. }
  8014. if (exprEvaluator.mIsVolatileReference)
  8015. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8016. }
  8017. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  8018. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8019. if (auto autoComplete = mCompiler->GetAutoComplete())
  8020. autoComplete->CheckResult(expr, typedVal);
  8021. return typedVal;
  8022. }
  8023. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  8024. {
  8025. BfExprEvaluator exprEvaluator(this);
  8026. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  8027. }
  8028. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  8029. {
  8030. BfExprEvaluator exprEvaluator(this);
  8031. exprEvaluator.Evaluate(expr);
  8032. if (!exprEvaluator.mResult)
  8033. {
  8034. Fail("Invalid expression type", expr);
  8035. return BfTypedValue();
  8036. }
  8037. if (!exprEvaluator.mResult.IsAddr())
  8038. {
  8039. Fail("Cannot assign to value", expr);
  8040. return BfTypedValue();
  8041. }
  8042. return exprEvaluator.mResult;
  8043. }
  8044. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  8045. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  8046. {
  8047. auto typeInstance = typedValue.mType->ToTypeInstance();
  8048. if (zeroMemory)
  8049. {
  8050. int zeroAlign = typedValue.mType->mAlign;
  8051. if (typeInstance != NULL)
  8052. zeroAlign = typeInstance->mInstAlign;
  8053. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  8054. }
  8055. if (!typedValue.mType->IsObject())
  8056. {
  8057. return;
  8058. }
  8059. if ((scopeData == NULL) && (mCurMethodState != NULL))
  8060. return; // Handled in heap alloc funcs
  8061. auto typeDef = typeInstance->mTypeDef;
  8062. mBfIRBuilder->PopulateType(typedValue.mType);
  8063. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  8064. bool isAutocomplete = mCompiler->IsAutocomplete();
  8065. BfIRValue vDataRef;
  8066. if (!isAutocomplete)
  8067. {
  8068. vDataRef = GetClassVDataPtr(typeInstance);
  8069. }
  8070. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8071. auto ptrType = CreatePointerType(i8Type);
  8072. auto ptrPtrType = CreatePointerType(ptrType);
  8073. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  8074. PopulateType(ptrType, BfPopulateType_Declaration);
  8075. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  8076. if (!isAutocomplete)
  8077. {
  8078. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8079. {
  8080. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8081. SizedArray<BfIRValue, 4> llvmArgs;
  8082. llvmArgs.push_back(objectPtr);
  8083. llvmArgs.push_back(vDataRef);
  8084. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  8085. if (objectStackInitMethod)
  8086. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  8087. }
  8088. else
  8089. {
  8090. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  8091. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  8092. mBfIRBuilder->CreateStore(srcVal, destAddr);
  8093. }
  8094. }
  8095. }
  8096. bool BfModule::IsAllocatorAligned()
  8097. {
  8098. if (mCompiler->mOptions.mMallocLinkName == "StompAlloc")
  8099. return false;
  8100. return true;
  8101. }
  8102. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  8103. {
  8104. BfIRValue result;
  8105. BfType* ptrType;
  8106. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  8107. ptrType = type;
  8108. else
  8109. ptrType = CreatePointerType(type);
  8110. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  8111. {
  8112. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8113. SizedArray<BfExpression*, 2> argExprs;
  8114. BfTypedValueExpression typedValueExpr;
  8115. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  8116. typedValueExpr.mRefNode = refNode;
  8117. argExprs.push_back(&typedValueExpr);
  8118. BfTypedValueExpression appendSizeValueExpr;
  8119. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  8120. appendSizeValueExpr.mRefNode = refNode;
  8121. argExprs.push_back(&appendSizeValueExpr);
  8122. BfExprEvaluator exprEvaluator(this);
  8123. BfTypedValue allocResult;
  8124. if (allocTarget.mScopedInvocationTarget != NULL)
  8125. {
  8126. SizedArray<BfTypeReference*, 2> genericArgs;
  8127. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, BfMethodGenericArguments());
  8128. allocResult = LoadValue(exprEvaluator.mResult);
  8129. }
  8130. else if (allocTarget.mCustomAllocator)
  8131. {
  8132. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8133. if (customTypeInst == NULL)
  8134. {
  8135. if (allocTarget.mCustomAllocator.mType->IsStructPtr())
  8136. customTypeInst = allocTarget.mCustomAllocator.mType->GetUnderlyingType()->ToTypeInstance();
  8137. }
  8138. if (customTypeInst == NULL)
  8139. {
  8140. Fail(StrFormat("Type '%s' cannot be used as a custom allocator", TypeToString(allocTarget.mCustomAllocator.mType).c_str()), refNode);
  8141. }
  8142. else
  8143. {
  8144. BfTypedValueExpression typeValueExpr;
  8145. String allocMethodName = "Alloc";
  8146. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  8147. {
  8148. allocMethodName = "AllocTyped";
  8149. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  8150. auto typeRefVal = CreateTypeDataRef(type);
  8151. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  8152. typeValueExpr.mRefNode = refNode;
  8153. argExprs.Insert(0, &typeValueExpr);
  8154. }
  8155. if (HasMixin(customTypeInst, allocMethodName, 2))
  8156. {
  8157. BfSizedArray<BfExpression*> argExprArr;
  8158. argExprArr.mSize = (int)argExprs.size();
  8159. argExprArr.mVals = &argExprs[0];
  8160. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  8161. allocResult = exprEvaluator.GetResult();
  8162. }
  8163. else
  8164. {
  8165. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8166. BfResolvedArgs argValues(&sizedArgExprs);
  8167. exprEvaluator.ResolveArgValues(argValues);
  8168. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  8169. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, BfMethodGenericArguments());
  8170. }
  8171. }
  8172. }
  8173. if (allocResult)
  8174. {
  8175. if (allocResult.mType->IsVoidPtr())
  8176. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  8177. else
  8178. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  8179. return result;
  8180. }
  8181. }
  8182. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  8183. return result;
  8184. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8185. {
  8186. BfIRValue allocData = GetDbgRawAllocData(type);
  8187. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  8188. SizedArray<BfIRValue, 2> llvmArgs;
  8189. llvmArgs.push_back(sizeValue);
  8190. llvmArgs.push_back(allocData);
  8191. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  8192. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8193. }
  8194. BfModuleMethodInstance moduleMethodInstance;
  8195. moduleMethodInstance = GetInternalMethod("Malloc");
  8196. SizedArray<BfIRValue, 1> llvmArgs;
  8197. llvmArgs.push_back(sizeValue);
  8198. auto func = moduleMethodInstance.mFunc;
  8199. if ((!func) || (func.IsFake()))
  8200. {
  8201. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  8202. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  8203. }
  8204. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  8205. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  8206. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  8207. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8208. return result;
  8209. }
  8210. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  8211. {
  8212. if (type->IsStruct())
  8213. {
  8214. auto typeInstance = type->ToTypeInstance();
  8215. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  8216. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8217. }
  8218. else if (type->IsObjectOrInterface())
  8219. {
  8220. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8221. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  8222. BF_ASSERT(moduleMethodInst.mFunc);
  8223. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8224. }
  8225. else
  8226. {
  8227. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8228. BfExprEvaluator exprEvaluator(this);
  8229. SizedArray<BfResolvedArg, 1> resolvedArgs;
  8230. BfResolvedArg resolvedArg;
  8231. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  8232. resolvedArgs.Add(resolvedArg);
  8233. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, BfMethodGenericArguments());
  8234. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  8235. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  8236. BF_ASSERT(moduleMethodInst.mFunc);
  8237. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8238. }
  8239. return BfIRValue();
  8240. }
  8241. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  8242. {
  8243. BfIRValue allocDataValue;
  8244. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  8245. return allocDataValue;
  8246. BfIRValue markFuncPtr;
  8247. if (type->WantsGCMarking())
  8248. markFuncPtr = GetMarkFuncPtr(type);
  8249. else
  8250. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8251. BfIRValue typeDataRef = CreateTypeDataRef(type);
  8252. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  8253. BfTypeInstance* typeInstance = type->ToTypeInstance();
  8254. if (typeInstance == NULL)
  8255. {
  8256. typeInstance = GetWrappedStructType(type);
  8257. if (typeInstance != NULL)
  8258. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8259. }
  8260. if (typeInstance != NULL)
  8261. PopulateType(typeInstance);
  8262. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8263. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  8264. {
  8265. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8266. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8267. }
  8268. SizedArray<BfIRValue, 2> dataValues;
  8269. dataValues.Add(mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  8270. dataValues.Add(typeDataRef);
  8271. dataValues.Add(markFuncPtr);
  8272. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  8273. BfIRValue dataStruct = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  8274. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  8275. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  8276. return allocDataValue;
  8277. }
  8278. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  8279. {
  8280. BP_ZONE("AllocFromType");
  8281. BfScopeData* scopeData = allocTarget.mScopeData;
  8282. BF_ASSERT(!type->IsVar());
  8283. auto typeInstance = type->ToTypeInstance();
  8284. if ((typeInstance == NULL) && (type->IsGenericParam()))
  8285. typeInstance = mContext->mBfObjectType;
  8286. bool isHeapAlloc = scopeData == NULL;
  8287. bool isScopeAlloc = scopeData != NULL;
  8288. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  8289. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  8290. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  8291. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  8292. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  8293. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  8294. {
  8295. BfPointerType* ptrType = CreatePointerType(type);
  8296. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  8297. return val;
  8298. }
  8299. if (typeInstance != NULL)
  8300. mBfIRBuilder->PopulateType(typeInstance);
  8301. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  8302. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  8303. {
  8304. return mBfIRBuilder->GetFakeVal();
  8305. }
  8306. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8307. BfIRValue sizeValue;
  8308. BfIRType allocType = mBfIRBuilder->MapType(type);
  8309. int allocSize = type->mSize;
  8310. int allocAlign = type->mAlign;
  8311. if (typeInstance != NULL)
  8312. {
  8313. if ((!mBfIRBuilder->mIgnoreWrites) && (!mIsComptimeModule))
  8314. typeInstance->mHasBeenInstantiated = true;
  8315. allocSize = typeInstance->mInstSize;
  8316. allocAlign = typeInstance->mInstAlign;
  8317. //if (typeInstance->IsEnum())
  8318. //allocType = typeInstance->mIRType;
  8319. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  8320. }
  8321. if (alignOverride != -1)
  8322. allocAlign = alignOverride;
  8323. // The "dynSize" cases:
  8324. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  8325. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  8326. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  8327. // though we'd expect their stack space to be released
  8328. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  8329. {
  8330. MarkDynStack(scopeData);
  8331. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8332. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  8333. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  8334. BfType* voidPtrType = CreatePointerType(voidType);
  8335. if (!mCurMethodState->mDynStackRevIdx)
  8336. {
  8337. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  8338. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8339. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8340. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  8341. mBfIRBuilder->ClearDebugLocation(storeInst);
  8342. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8343. }
  8344. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  8345. auto bytePtrType = CreatePointerType(byteType);
  8346. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  8347. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  8348. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8349. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8350. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  8351. mBfIRBuilder->ClearDebugLocation(storeInst);
  8352. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  8353. mBfIRBuilder->ClearDebugLocation(storeInst);
  8354. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8355. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  8356. if (IsTargetingBeefBackend())
  8357. {
  8358. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  8359. // to ensure there isn't any register collision during looping is just to not allow it to
  8360. // bind to a register at all
  8361. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  8362. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  8363. }
  8364. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  8365. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  8366. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  8367. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  8368. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  8369. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  8370. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  8371. mBfIRBuilder->AddBlock(verCheckBB);
  8372. mBfIRBuilder->SetInsertPoint(verCheckBB);
  8373. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  8374. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  8375. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  8376. mBfIRBuilder->AddBlock(resizeBB);
  8377. mBfIRBuilder->SetInsertPoint(resizeBB);
  8378. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8379. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  8380. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  8381. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  8382. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  8383. mBfIRBuilder->CreateBr(endBB);
  8384. mBfIRBuilder->AddBlock(endBB);
  8385. mBfIRBuilder->SetInsertPoint(endBB);
  8386. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  8387. };
  8388. if (isScopeAlloc)
  8389. {
  8390. if (arraySize)
  8391. {
  8392. bool isConstantArraySize = arraySize.IsConst();
  8393. if (isRawArrayAlloc)
  8394. {
  8395. BfPointerType* ptrType = CreatePointerType(type);
  8396. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8397. {
  8398. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8399. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  8400. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  8401. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  8402. }
  8403. else
  8404. {
  8405. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8406. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  8407. if (!isDynAlloc)
  8408. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8409. else
  8410. {
  8411. MarkDynStack(scopeData);
  8412. SaveStackState(scopeData);
  8413. }
  8414. int typeSize = type->GetStride();
  8415. BfIRValue allocaInst;
  8416. BfIRValue result;
  8417. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  8418. {
  8419. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  8420. result = allocaInst;
  8421. }
  8422. else
  8423. {
  8424. if (typeInstance->IsStruct())
  8425. typeSize = typeInstance->GetInstStride();
  8426. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  8427. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  8428. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8429. auto ptrType = CreatePointerType(typeInstance);
  8430. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  8431. if (!isDynAlloc)
  8432. mBfIRBuilder->ClearDebugLocation(result);
  8433. }
  8434. if (!isDynAlloc)
  8435. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8436. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8437. if (!isDynAlloc)
  8438. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8439. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  8440. if (arraySize.IsConst())
  8441. {
  8442. auto constant = mBfIRBuilder->GetConstant(arraySize);
  8443. if (constant->mInt64 == 0)
  8444. noDtorCall = true;
  8445. }
  8446. if (!noDtorCall)
  8447. {
  8448. bool isConstSize = arraySize.IsConst();
  8449. BfIRBlock clearBlock;
  8450. BfIRBlock contBlock;
  8451. bool wantsDeinit = ((!IsOptimized()) && (!mIsComptimeModule) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly));
  8452. if (wantsDeinit)
  8453. {
  8454. BfIRBlock prevBlock;
  8455. if (!isConstSize)
  8456. {
  8457. clearBlock = mBfIRBuilder->CreateBlock("clear");
  8458. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  8459. prevBlock = mBfIRBuilder->GetInsertBlock();
  8460. mBfIRBuilder->AddBlock(clearBlock);
  8461. mBfIRBuilder->SetInsertPoint(clearBlock);
  8462. }
  8463. auto deferredCall = AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  8464. if (!isConstSize)
  8465. {
  8466. mBfIRBuilder->CreateBr(contBlock);
  8467. mBfIRBuilder->SetInsertPoint(prevBlock);
  8468. if (deferredCall != NULL)
  8469. {
  8470. // Zero out size args
  8471. for (int i = 1; i < deferredCall->mModuleMethodInstance.mMethodInstance->GetParamCount(); i++)
  8472. {
  8473. auto scopedArg = deferredCall->mScopeArgs[i];
  8474. if (scopedArg != deferredCall->mOrigScopeArgs[i])
  8475. mBfIRBuilder->CreateStore(GetDefaultValue(deferredCall->mModuleMethodInstance.mMethodInstance->GetParamType(i)), deferredCall->mScopeArgs[i]);
  8476. }
  8477. }
  8478. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  8479. mBfIRBuilder->AddBlock(contBlock);
  8480. mBfIRBuilder->SetInsertPoint(contBlock);
  8481. }
  8482. }
  8483. }
  8484. return result;
  8485. }
  8486. }
  8487. else
  8488. {
  8489. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8490. {
  8491. // Generate and check new size
  8492. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8493. auto firstElementField = &arrayType->mFieldInstances.back();
  8494. int arrayClassSize = firstElementField->mDataOffset;
  8495. sizeValue = GetConstValue(arrayClassSize);
  8496. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8497. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8498. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  8499. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  8500. if (!noDtorCall)
  8501. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8502. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8503. return typedVal.mValue;
  8504. }
  8505. else
  8506. {
  8507. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8508. auto firstElementField = &arrayType->mFieldInstances.back();
  8509. if (!type->IsValuelessType())
  8510. {
  8511. int arrayClassSize = firstElementField->mDataOffset;
  8512. sizeValue = GetConstValue(arrayClassSize);
  8513. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8514. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8515. }
  8516. else
  8517. sizeValue = GetConstValue(arrayType->mInstSize);
  8518. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8519. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8520. if (!isDynAlloc)
  8521. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8522. else
  8523. {
  8524. MarkDynStack(scopeData);
  8525. SaveStackState(scopeData);
  8526. }
  8527. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  8528. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8529. if (!isDynAlloc)
  8530. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8531. auto allocaBlock = mBfIRBuilder->GetInsertBlock();
  8532. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8533. BfTypedValue typedVal;
  8534. if (!isDynAlloc)
  8535. {
  8536. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8537. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8538. mBfIRBuilder->ClearDebugLocation(typedVal.mValue);
  8539. mBfIRBuilder->SetInsertPoint(prevBlock);
  8540. allocaBlock = mCurMethodState->mIRInitBlock;
  8541. }
  8542. else
  8543. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8544. if (!noDtorCall)
  8545. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true, allocaBlock);
  8546. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8547. return typedVal.mValue;
  8548. }
  8549. }
  8550. }
  8551. else if (appendSizeValue)
  8552. {
  8553. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  8554. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  8555. // use the "dynSize" version conservatively
  8556. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8557. {
  8558. // Generate and check new size
  8559. sizeValue = GetConstValue(typeInstance->mInstSize);
  8560. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8561. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  8562. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  8563. if (!noDtorCall)
  8564. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  8565. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8566. return typedVal.mValue;
  8567. }
  8568. else // stack alloc, unlooped, with append
  8569. {
  8570. sizeValue = GetConstValue(typeInstance->mInstSize);
  8571. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8572. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8573. bool wasDynAlloc = isDynAlloc;
  8574. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8575. if (!isDynAlloc)
  8576. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8577. else
  8578. {
  8579. MarkDynStack(scopeData);
  8580. SaveStackState(scopeData);
  8581. }
  8582. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  8583. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  8584. if (!isDynAlloc)
  8585. {
  8586. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8587. }
  8588. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8589. bool mayBeLarge = false;
  8590. if (sizeValue.IsConst())
  8591. {
  8592. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  8593. if (constantInt->mInt64 >= 4096)
  8594. mayBeLarge = true;
  8595. }
  8596. else
  8597. mayBeLarge = true;
  8598. if (((type->IsObject() && (!mayBeLarge))) ||
  8599. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8600. ((zeroMemory) && (!mayBeLarge)))
  8601. {
  8602. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8603. }
  8604. BfIRValue castedVal;
  8605. if (!isDynAlloc)
  8606. {
  8607. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8608. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8609. mBfIRBuilder->ClearDebugLocation(castedVal);
  8610. mBfIRBuilder->SetInsertPoint(prevBlock);
  8611. if (WantsLifetimes())
  8612. {
  8613. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8614. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8615. }
  8616. }
  8617. else
  8618. {
  8619. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8620. }
  8621. auto typedVal = BfTypedValue(castedVal, typeInstance);
  8622. if (!noDtorCall)
  8623. {
  8624. bool doCondAlloca = false;
  8625. if (!IsTargetingBeefBackend())
  8626. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  8627. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  8628. }
  8629. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8630. return typedVal.mValue;
  8631. }
  8632. }
  8633. else // "Normal" stack alloc
  8634. {
  8635. BF_ASSERT(!sizeValue);
  8636. //TODO: If sizeValue is a constant then do this in the head IR builder
  8637. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8638. if (!isLoopedAlloc)
  8639. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8640. else
  8641. {
  8642. MarkDynStack(scopeData);
  8643. SaveStackState(scopeData);
  8644. }
  8645. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  8646. if (!isLoopedAlloc)
  8647. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8648. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8649. bool mayBeLarge = allocSize >= 4096;
  8650. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  8651. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8652. ((zeroMemory) && (!mayBeLarge)))
  8653. {
  8654. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  8655. // and memset is always safe
  8656. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8657. }
  8658. auto typedVal = BfTypedValue(allocaInst, type);
  8659. if (!isLoopedAlloc)
  8660. {
  8661. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8662. mBfIRBuilder->SetInsertPoint(prevBlock);
  8663. if (WantsLifetimes())
  8664. {
  8665. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8666. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8667. }
  8668. }
  8669. if (!noDtorCall)
  8670. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8671. if (typeInstance != NULL)
  8672. {
  8673. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  8674. }
  8675. else
  8676. {
  8677. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  8678. }
  8679. return allocaInst;
  8680. }
  8681. }
  8682. else if (arraySize)
  8683. {
  8684. if (isRawArrayAlloc)
  8685. {
  8686. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8687. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  8688. }
  8689. else
  8690. {
  8691. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8692. typeInstance = arrayType;
  8693. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8694. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8695. appendSizeValue = elementDataSize;
  8696. if (!type->IsSizeAligned())
  8697. {
  8698. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  8699. }
  8700. }
  8701. }
  8702. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  8703. {
  8704. auto vDataRef = GetClassVDataPtr(typeInstance);
  8705. BfIRValue result;
  8706. bool isResultInitialized = false;
  8707. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8708. if (typeInstance->mTypeOptionsIdx != -1)
  8709. {
  8710. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8711. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8712. }
  8713. if (mIsComptimeModule)
  8714. stackCount = 0;
  8715. if (!sizeValue)
  8716. sizeValue = GetConstValue(typeInstance->mInstSize);
  8717. if (appendSizeValue)
  8718. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8719. BfIRValue origSizeValue = sizeValue;
  8720. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  8721. if (isAllocEx)
  8722. {
  8723. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  8724. if (prepareStackTraceMethod)
  8725. {
  8726. SizedArray<BfIRValue, 2> irArgs;
  8727. irArgs.Add(sizeValue);
  8728. irArgs.Add(GetConstValue(stackCount));
  8729. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  8730. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  8731. }
  8732. }
  8733. if (allocTarget.mCustomAllocator)
  8734. {
  8735. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8736. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  8737. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  8738. {
  8739. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8740. mBfIRBuilder->PopulateType(classVDataType);
  8741. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8742. mBfIRBuilder->PopulateType(typeInstType);
  8743. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  8744. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  8745. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  8746. BfTypedValueExpression typedValueExpr;
  8747. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  8748. typedValueExpr.mRefNode = allocTarget.mRefNode;
  8749. BfExprEvaluator exprEvaluator(this);
  8750. SizedArray<BfExpression*, 2> argExprs;
  8751. argExprs.push_back(&typedValueExpr);
  8752. BfTypedValueExpression sizeValueExpr;
  8753. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  8754. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  8755. argExprs.push_back(&sizeValueExpr);
  8756. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8757. BfResolvedArgs argValues(&sizedArgExprs);
  8758. exprEvaluator.ResolveArgValues(argValues);
  8759. exprEvaluator.mNoBind = true;
  8760. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, BfMethodGenericArguments());
  8761. if (allocResult)
  8762. {
  8763. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  8764. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  8765. else
  8766. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  8767. isResultInitialized = true;
  8768. }
  8769. }
  8770. }
  8771. bool wasAllocated = false;
  8772. if (!result)
  8773. {
  8774. if (hasCustomAllocator)
  8775. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  8776. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8777. {
  8778. SizedArray<BfIRValue, 4> llvmArgs;
  8779. llvmArgs.push_back(sizeValue);
  8780. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8781. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8782. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8783. wasAllocated = true;
  8784. }
  8785. }
  8786. if (result)
  8787. {
  8788. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8789. {
  8790. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  8791. SizedArray<BfIRValue, 4> llvmArgs;
  8792. llvmArgs.push_back(objectPtr);
  8793. llvmArgs.push_back(origSizeValue);
  8794. llvmArgs.push_back(vDataRef);
  8795. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  8796. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  8797. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  8798. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  8799. if (wasAllocated)
  8800. {
  8801. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  8802. auto bytePtrType = CreatePointerType(byteType);
  8803. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  8804. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  8805. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  8806. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  8807. }
  8808. }
  8809. else
  8810. {
  8811. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  8812. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8813. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  8814. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  8815. }
  8816. }
  8817. else
  8818. {
  8819. if ((mBfIRBuilder->mIgnoreWrites) ||
  8820. ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)))
  8821. {
  8822. if (mBfIRBuilder->mIgnoreWrites)
  8823. {
  8824. return GetDefaultValue(typeInstance);
  8825. }
  8826. else
  8827. {
  8828. // Fake with alloca
  8829. mBfIRBuilder->PopulateType(typeInstance);
  8830. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInstance));
  8831. }
  8832. }
  8833. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8834. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  8835. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8836. {
  8837. SizedArray<BfIRValue, 4> llvmArgs;
  8838. llvmArgs.push_back(vData);
  8839. llvmArgs.push_back(sizeValue);
  8840. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  8841. llvmArgs.push_back(GetConstValue(stackCount));
  8842. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  8843. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  8844. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8845. }
  8846. else
  8847. {
  8848. SizedArray<BfIRValue, 4> llvmArgs;
  8849. llvmArgs.push_back(sizeValue);
  8850. BfIRFunction irFunc;
  8851. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8852. {
  8853. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  8854. irFunc = moduleMethodInstance.mFunc;
  8855. }
  8856. if (!irFunc)
  8857. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8858. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8859. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  8860. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  8861. if (mIsComptimeModule)
  8862. {
  8863. vdataPtr = mBfIRBuilder->CreateBitCast(vdataPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance())));
  8864. }
  8865. mBfIRBuilder->CreateStore(vData, vdataPtr);
  8866. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8867. }
  8868. }
  8869. if ((zeroMemory) && (arraySize))
  8870. {
  8871. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8872. typeInstance = arrayType;
  8873. auto firstElementField = &arrayType->mFieldInstances.back();
  8874. int arrayClassSize = firstElementField->mDataOffset;
  8875. BfIRValue elementDataSize;
  8876. bool skipZero = false;
  8877. if (arraySize.IsConst())
  8878. {
  8879. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8880. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8881. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  8882. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  8883. if (constVal->mInt64 <= 0)
  8884. skipZero = true;
  8885. }
  8886. else
  8887. {
  8888. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  8889. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8890. }
  8891. if (!skipZero)
  8892. {
  8893. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8894. auto ptrType = CreatePointerType(i8Type);
  8895. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  8896. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  8897. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  8898. appendSizeValue = elementDataSize;
  8899. }
  8900. }
  8901. return result;
  8902. }
  8903. else
  8904. {
  8905. if (!sizeValue)
  8906. sizeValue = GetConstValue(allocSize);
  8907. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  8908. }
  8909. }
  8910. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  8911. {
  8912. if ((type == NULL) || (refNode == NULL))
  8913. return;
  8914. auto typeInstance = type->ToTypeInstance();
  8915. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  8916. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  8917. }
  8918. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  8919. {
  8920. if (align <= 1)
  8921. return;
  8922. if (sizeMultiple == 0)
  8923. sizeMultiple = align;
  8924. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  8925. {
  8926. if (!IsAllocatorAligned())
  8927. {
  8928. // Don't align
  8929. }
  8930. else if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  8931. {
  8932. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8933. BF_ASSERT(localVar->mName == "appendIdx");
  8934. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  8935. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8936. if (align > 1)
  8937. {
  8938. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8939. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8940. }
  8941. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  8942. }
  8943. else
  8944. {
  8945. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  8946. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  8947. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  8948. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8949. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8950. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  8951. }
  8952. }
  8953. if (mCurMethodState->mCurAppendAlign == 0)
  8954. mCurMethodState->mCurAppendAlign = sizeMultiple;
  8955. else
  8956. {
  8957. if (sizeMultiple % align == 0)
  8958. mCurMethodState->mCurAppendAlign = align;
  8959. else
  8960. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  8961. }
  8962. }
  8963. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  8964. {
  8965. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8966. BF_ASSERT(localVar->mName == "appendIdx");
  8967. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  8968. BfIRValue retValue;
  8969. BfTypeInstance* retTypeInstance = NULL;
  8970. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  8971. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  8972. if (arraySize)
  8973. {
  8974. if (isRawArrayAlloc)
  8975. {
  8976. EmitAppendAlign(type->mAlign);
  8977. BfPointerType* ptrType = CreatePointerType(type);
  8978. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8979. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8980. if (mSystem->mPtrSize != 4)
  8981. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8982. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8983. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8984. if (zeroMemory)
  8985. {
  8986. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  8987. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  8988. }
  8989. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  8990. }
  8991. else
  8992. {
  8993. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8994. EmitAppendAlign(arrayType->mAlign, type->mSize);
  8995. auto firstElementField = &arrayType->mFieldInstances.back();
  8996. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  8997. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  8998. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8999. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  9000. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9001. if (mSystem->mPtrSize != 4)
  9002. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  9003. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9004. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9005. if (zeroMemory)
  9006. {
  9007. // Only zero out the actual elements
  9008. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  9009. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  9010. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  9011. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  9012. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  9013. }
  9014. retTypeInstance = arrayType;
  9015. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  9016. }
  9017. }
  9018. else
  9019. {
  9020. auto typeInst = type->ToTypeInstance();
  9021. BfIRValue sizeValue;
  9022. BfIRType toType;
  9023. if (typeInst != NULL)
  9024. {
  9025. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  9026. sizeValue = GetConstValue(typeInst->mInstSize);
  9027. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  9028. }
  9029. else
  9030. {
  9031. EmitAppendAlign(type->mAlign, type->mSize);
  9032. sizeValue = GetConstValue(type->mSize);
  9033. auto toPtrType = CreatePointerType(type);
  9034. toType = mBfIRBuilder->MapType(toPtrType);
  9035. }
  9036. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9037. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9038. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9039. retTypeInstance = typeInst;
  9040. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  9041. }
  9042. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  9043. {
  9044. mBfIRBuilder->PopulateType(retTypeInstance);
  9045. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  9046. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  9047. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  9048. auto curThis = GetThis();
  9049. BfIRValue newFlags;
  9050. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9051. {
  9052. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  9053. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  9054. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  9055. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  9056. }
  9057. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  9058. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  9059. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  9060. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  9061. mBfIRBuilder->CreateStore(srcVal, destAddr);
  9062. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9063. {
  9064. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  9065. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  9066. }
  9067. }
  9068. if (appendSizeValue)
  9069. {
  9070. EmitAppendAlign(appendAllocAlign);
  9071. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9072. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  9073. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9074. }
  9075. return retValue;
  9076. }
  9077. bool BfModule::IsOptimized()
  9078. {
  9079. if (mProject == NULL)
  9080. return false;
  9081. if (mIsComptimeModule)
  9082. return false;
  9083. int optLevel = GetModuleOptions().mOptLevel;
  9084. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  9085. }
  9086. bool BfModule::IsTargetingBeefBackend()
  9087. {
  9088. if (mProject == NULL)
  9089. return true;
  9090. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9091. }
  9092. bool BfModule::WantsLifetimes()
  9093. {
  9094. if (mBfIRBuilder->mIgnoreWrites)
  9095. return false;
  9096. if ((mIsComptimeModule) && (mBfIRBuilder->HasDebugLocation()))
  9097. return true;
  9098. else if (mProject == NULL)
  9099. return false;
  9100. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9101. }
  9102. bool BfModule::HasCompiledOutput()
  9103. {
  9104. return (!mSystem->mIsResolveOnly) && (mGeneratesCode) && (!mIsComptimeModule);
  9105. }
  9106. bool BfModule::HasExecutedOutput()
  9107. {
  9108. return ((!mSystem->mIsResolveOnly) && (mGeneratesCode)) || (mIsComptimeModule);
  9109. }
  9110. // We will skip the object access check for any occurrences of this value
  9111. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  9112. {
  9113. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9114. return;
  9115. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9116. return;
  9117. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  9118. return;
  9119. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  9120. }
  9121. bool BfModule::WantsObjectAccessCheck(BfType* type)
  9122. {
  9123. if ((mBfIRBuilder->mIgnoreWrites) || (!type->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9124. return false;
  9125. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9126. return false;
  9127. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9128. auto typeOptions = GetTypeOptions();
  9129. if (typeOptions != NULL)
  9130. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9131. if (!emitObjectAccessCheck)
  9132. return false;
  9133. return true;
  9134. }
  9135. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  9136. {
  9137. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9138. return;
  9139. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9140. return;
  9141. if (typedVal.mValue.IsConst())
  9142. {
  9143. int stringIdx = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  9144. if (stringIdx != -1)
  9145. return;
  9146. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  9147. if (constant->mTypeCode == BfTypeCode_NullPtr)
  9148. return;
  9149. if (constant->mConstType == BfConstType_BitCastNull)
  9150. return;
  9151. }
  9152. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9153. auto typeOptions = GetTypeOptions();
  9154. if (typeOptions != NULL)
  9155. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9156. if (!emitObjectAccessCheck)
  9157. return;
  9158. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  9159. {
  9160. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  9161. return;
  9162. }
  9163. if (typedVal.IsAddr())
  9164. typedVal = LoadValue(typedVal);
  9165. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  9166. }
  9167. bool BfModule::WantsDebugHelpers()
  9168. {
  9169. if (mBfIRBuilder->mIgnoreWrites)
  9170. return false;
  9171. if (mIsComptimeModule)
  9172. {
  9173. // Always add
  9174. }
  9175. else if ((mProject == NULL) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  9176. return false;
  9177. return true;
  9178. }
  9179. void BfModule::EmitEnsureInstructionAt()
  9180. {
  9181. if (!WantsDebugHelpers())
  9182. return;
  9183. mBfIRBuilder->CreateEnsureInstructionAt();
  9184. }
  9185. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  9186. {
  9187. if (mBfIRBuilder->mIgnoreWrites)
  9188. return; // Nothing needed here
  9189. auto irb = mBfIRBuilder;
  9190. auto checkBB = irb->CreateBlock("as.check");
  9191. auto isNull = irb->CreateIsNull(targetValue.mValue);
  9192. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  9193. if (mIsComptimeModule)
  9194. {
  9195. AddBasicBlock(checkBB);
  9196. auto callResult = mBfIRBuilder->Comptime_DynamicCastCheck(targetValue.mValue, targetType->mTypeId, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9197. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult, GetDefaultValue(mContext->mBfObjectType));
  9198. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9199. return;
  9200. }
  9201. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  9202. auto intPtrType = CreatePointerType(intType);
  9203. auto intPtrPtrType = CreatePointerType(intPtrType);
  9204. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  9205. auto int32PtrType = CreatePointerType(int32Type);
  9206. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  9207. if (mCompiler->mOptions.mAllowHotSwapping)
  9208. {
  9209. BfExprEvaluator exprEvaluator(this);
  9210. AddBasicBlock(checkBB);
  9211. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9212. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  9213. SizedArray<BfIRValue, 4> irArgs;
  9214. irArgs.push_back(objectParam);
  9215. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  9216. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  9217. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  9218. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9219. }
  9220. else
  9221. {
  9222. AddBasicBlock(checkBB);
  9223. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  9224. vDataPtr = irb->CreateLoad(vDataPtr);
  9225. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9226. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  9227. if (targetType->IsInterface())
  9228. {
  9229. auto targetTypeInst = targetType->ToTypeInstance();
  9230. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9231. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  9232. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  9233. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9234. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  9235. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  9236. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  9237. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  9238. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  9239. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9240. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  9241. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  9242. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9243. }
  9244. else
  9245. {
  9246. if (!targetType->IsTypeInstance())
  9247. targetType = GetWrappedStructType(targetType);
  9248. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9249. int inheritanceIdOfs = mSystem->mPtrSize * mCompiler->GetVDataPrefixDataCount();
  9250. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9251. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9252. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  9253. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  9254. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  9255. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  9256. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  9257. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9258. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  9259. fieldInst = &typeTypeInstance->mFieldInstances[10];
  9260. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  9261. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9262. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  9263. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  9264. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  9265. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9266. }
  9267. }
  9268. }
  9269. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  9270. {
  9271. if (mBfIRBuilder->mIgnoreWrites)
  9272. return;
  9273. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  9274. auto typeOptions = GetTypeOptions();
  9275. if (typeOptions != NULL)
  9276. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  9277. if (emitDynamicCastCheck)
  9278. {
  9279. int wantTypeId = 0;
  9280. if (!type->IsGenericParam())
  9281. wantTypeId = type->mTypeId;
  9282. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  9283. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  9284. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  9285. AddBasicBlock(failBlock);
  9286. if (mIsComptimeModule)
  9287. {
  9288. mBfIRBuilder->Comptime_Error(CeErrorKind_ObjectDynCheckFailed);
  9289. }
  9290. else
  9291. {
  9292. SizedArray<BfIRValue, 8> llvmArgs;
  9293. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9294. llvmArgs.push_back(bitAddr);
  9295. llvmArgs.push_back(GetConstValue32(wantTypeId));
  9296. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  9297. BF_ASSERT(objDynCheck);
  9298. if (objDynCheck)
  9299. {
  9300. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  9301. }
  9302. }
  9303. mBfIRBuilder->CreateBr(endBlock);
  9304. AddBasicBlock(endBlock);
  9305. }
  9306. }
  9307. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, BfCastFlags castFlags)
  9308. {
  9309. bool callDtor = (castFlags & BfCastFlags_NoBoxDtor) == 0;
  9310. bool wantConst = ((castFlags & BfCastFlags_WantsConst) != 0) && (typedVal.mValue.IsConst());
  9311. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9312. {
  9313. if (toType == mContext->mBfObjectType)
  9314. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9315. if (toType->IsBoxed())
  9316. {
  9317. BfBoxedType* boxedType = (BfBoxedType*)toType;
  9318. if (boxedType->mElementType->IsGenericParam())
  9319. {
  9320. if (typedVal.mType == boxedType->mElementType)
  9321. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9322. else
  9323. return BfTypedValue();
  9324. }
  9325. }
  9326. }
  9327. BP_ZONE("BoxValue");
  9328. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  9329. if (typedVal.mType->IsNullable())
  9330. {
  9331. typedVal = MakeAddressable(typedVal);
  9332. auto innerType = typedVal.mType->GetUnderlyingType();
  9333. if (!innerType->IsValueType())
  9334. {
  9335. if (!mIgnoreErrors)
  9336. Fail("Only value types can be boxed", srcNode);
  9337. return BfTypedValue();
  9338. }
  9339. auto boxedType = CreateBoxedType(innerType);
  9340. auto resultType = toType;
  9341. if (resultType == NULL)
  9342. resultType = boxedType;
  9343. if (mBfIRBuilder->mIgnoreWrites)
  9344. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  9345. auto prevBB = mBfIRBuilder->GetInsertBlock();
  9346. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  9347. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  9348. mBfIRBuilder->PopulateType(typedVal.mType);
  9349. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  9350. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  9351. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  9352. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9353. mBfIRBuilder->AddBlock(boxBB);
  9354. mBfIRBuilder->SetInsertPoint(boxBB);
  9355. BfScopeData newScope;
  9356. newScope.mOuterIsConditional = true;
  9357. mCurMethodState->AddScope(&newScope);
  9358. NewScopeState();
  9359. BfIRValue nullableValueAddr;
  9360. BfIRValue loadedVal;
  9361. if (innerType->IsValuelessType())
  9362. {
  9363. loadedVal = mBfIRBuilder->GetFakeVal();
  9364. }
  9365. else
  9366. {
  9367. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  9368. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  9369. }
  9370. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor ? BfCastFlags_None : BfCastFlags_NoBoxDtor);
  9371. RestoreScopeState();
  9372. if (!boxedVal)
  9373. return BfTypedValue();
  9374. mBfIRBuilder->CreateBr(endBB);
  9375. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  9376. mBfIRBuilder->AddBlock(endBB);
  9377. mBfIRBuilder->SetInsertPoint(endBB);
  9378. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  9379. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  9380. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  9381. return BfTypedValue(phi, resultType);
  9382. }
  9383. bool alreadyCheckedCast = false;
  9384. BfTypeInstance* toTypeInstance = NULL;
  9385. if (toType != NULL)
  9386. toTypeInstance = toType->ToTypeInstance();
  9387. bool isStructPtr = typedVal.mType->IsStructPtr();
  9388. if (fromStructTypeInstance == NULL)
  9389. {
  9390. auto primType = (BfPrimitiveType*)typedVal.mType;
  9391. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  9392. {
  9393. // Can always do IHashable
  9394. alreadyCheckedCast = true;
  9395. }
  9396. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  9397. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9398. else
  9399. {
  9400. auto checkStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9401. if (checkStructTypeInstance == toType->GetUnderlyingType())
  9402. fromStructTypeInstance = checkStructTypeInstance;
  9403. }
  9404. if (isStructPtr)
  9405. {
  9406. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9407. alreadyCheckedCast = true;
  9408. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  9409. }
  9410. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  9411. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9412. }
  9413. if (fromStructTypeInstance == NULL)
  9414. return BfTypedValue();
  9415. // Need to box it
  9416. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  9417. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9418. {
  9419. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9420. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  9421. auto boxedType = CreateBoxedType(typedVal.mType);
  9422. mBfIRBuilder->PopulateType(boxedType);
  9423. if (wantConst)
  9424. return BfTypedValue(mBfIRBuilder->CreateConstBox(typedVal.mValue, mBfIRBuilder->MapType(boxedType)), boxedType);
  9425. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9426. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  9427. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  9428. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  9429. if (boxedType->IsUnspecializedType())
  9430. {
  9431. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  9432. }
  9433. else
  9434. {
  9435. PopulateType(fromStructTypeInstance);
  9436. if (!fromStructTypeInstance->IsValuelessType())
  9437. {
  9438. typedVal = LoadValue(typedVal);
  9439. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  9440. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  9441. {
  9442. auto ptrType = CreatePointerType(typedVal.mType);
  9443. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  9444. }
  9445. if (typedVal.IsSplat())
  9446. {
  9447. AggregateSplatIntoAddr(typedVal, valPtr);
  9448. }
  9449. else
  9450. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr, typedVal.mType->mAlign);
  9451. }
  9452. }
  9453. if (toType == NULL)
  9454. {
  9455. return BfTypedValue(allocaInst, boxedType);
  9456. }
  9457. else
  9458. {
  9459. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  9460. return BfTypedValue(castedValue, toType);
  9461. }
  9462. }
  9463. return BfTypedValue();
  9464. }
  9465. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  9466. {
  9467. BfTypeInstance* checkTypeInst = typeInst;
  9468. while (checkTypeInst != NULL)
  9469. {
  9470. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  9471. {
  9472. if (checkProp->mName == propDef->mName)
  9473. {
  9474. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  9475. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  9476. {
  9477. propDef = checkProp;
  9478. typeInst = checkTypeInst;
  9479. return true;
  9480. }
  9481. }
  9482. }
  9483. checkTypeInst = checkTypeInst->mBaseType;
  9484. }
  9485. return false;
  9486. }
  9487. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  9488. {
  9489. if (!typeInstance->mResolvingVarField)
  9490. {
  9491. if (!typeInstance->DefineStateAllowsStaticMethods())
  9492. PopulateType(typeInstance, BfPopulateType_AllowStaticMethods);
  9493. }
  9494. else
  9495. {
  9496. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  9497. {
  9498. AssertErrorState();
  9499. return NULL;
  9500. }
  9501. }
  9502. if (assertName != NULL)
  9503. {
  9504. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9505. }
  9506. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9507. {
  9508. if (mCompiler->EnsureCeUnpaused(typeInstance))
  9509. {
  9510. BF_FATAL("OOB in GetRawMethodInstanceAtIdx");
  9511. }
  9512. return NULL;
  9513. }
  9514. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  9515. if (methodGroup.mDefault == NULL)
  9516. {
  9517. if (!mCompiler->mIsResolveOnly)
  9518. {
  9519. // Get it from the owning module so we don't create a reference prematurely...
  9520. auto declModule = typeInstance->mModule;
  9521. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  9522. {
  9523. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9524. if (!declModule->mIsScratchModule)
  9525. declModule->mOnDemandMethodCount++;
  9526. }
  9527. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  9528. (typeInstance->mTypeFailed) || (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted));
  9529. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  9530. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9531. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified);
  9532. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9533. }
  9534. else
  9535. {
  9536. auto declModule = typeInstance->mModule;
  9537. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass);
  9538. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9539. }
  9540. }
  9541. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9542. //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
  9543. // be from a call to the NON-raw version
  9544. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  9545. // {
  9546. // methodInstance->mIsReified = mIsReified;
  9547. // if (methodInstance->mMethodProcessRequest == NULL)
  9548. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  9549. // }
  9550. return methodInstance;
  9551. }
  9552. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  9553. {
  9554. if (methodDef->mIsLocalMethod)
  9555. {
  9556. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  9557. }
  9558. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx, NULL);
  9559. }
  9560. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  9561. {
  9562. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9563. while (typeInstance != NULL)
  9564. {
  9565. typeInstance->mTypeDef->PopulateMemberSets();
  9566. BfMemberSetEntry* entry = NULL;
  9567. BfMethodDef* methodDef = NULL;
  9568. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9569. methodDef = (BfMethodDef*)entry->mMemberDef;
  9570. while (methodDef != NULL)
  9571. {
  9572. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  9573. (methodDef->mGenericParams.size() == 0) &&
  9574. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9575. return GetRawMethodInstance(typeInstance, methodDef);
  9576. methodDef = methodDef->mNextWithSameName;
  9577. }
  9578. if (!checkBase)
  9579. break;
  9580. typeInstance = typeInstance->mBaseType;
  9581. }
  9582. return NULL;
  9583. }
  9584. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  9585. {
  9586. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9587. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  9588. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  9589. if (!useUnspecializedType)
  9590. return methodInstance;
  9591. if (!owner->IsGenericTypeInstance())
  9592. return methodInstance;
  9593. if ((owner->IsDelegateFromTypeRef()) ||
  9594. (owner->IsFunctionFromTypeRef()) ||
  9595. (owner->IsTuple()))
  9596. {
  9597. return methodInstance;
  9598. }
  9599. auto genericType = (BfTypeInstance*)owner;
  9600. if ((genericType->IsUnspecializedType()) && (!genericType->IsUnspecializedTypeVariation()))
  9601. return methodInstance;
  9602. if (methodInstance->mMethodDef->mIsLocalMethod)
  9603. return methodInstance;
  9604. if (methodInstance->mMethodDef->mDeclaringType->IsEmitted())
  9605. return methodInstance;
  9606. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef->GetDefinition());
  9607. if (unspecializedType == NULL)
  9608. {
  9609. AssertErrorState();
  9610. return methodInstance;
  9611. }
  9612. if (unspecializedType == NULL)
  9613. return methodInstance;
  9614. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  9615. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  9616. }
  9617. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  9618. {
  9619. int genericCount = 0;
  9620. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  9621. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  9622. {
  9623. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  9624. if (param->IsGenericParam())
  9625. genericCount++;
  9626. }
  9627. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  9628. genericCount++;
  9629. return genericCount;
  9630. }
  9631. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  9632. {
  9633. BF_ASSERT(!mIsScratchModule);
  9634. BF_ASSERT(mIsReified);
  9635. BfModule* mainModule = this;
  9636. if (mParentModule != NULL)
  9637. mainModule = mParentModule;
  9638. BfModule* specModule = NULL;
  9639. BfModule** specModulePtr = NULL;
  9640. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  9641. {
  9642. return *specModulePtr;
  9643. }
  9644. else
  9645. {
  9646. String specModuleName = mModuleName;
  9647. for (auto bfProject : projectList)
  9648. {
  9649. specModuleName += StrFormat("@%s", bfProject->mSafeName.c_str());
  9650. }
  9651. specModule = new BfModule(mContext, specModuleName);
  9652. specModule->mProject = mainModule->mProject;
  9653. specModule->mParentModule = mainModule;
  9654. specModule->mIsSpecializedMethodModuleRoot = true;
  9655. specModule->Init();
  9656. Array<BfProject*> projList;
  9657. for (auto project : projectList)
  9658. projList.Add(project);
  9659. mainModule->mSpecializedMethodModules[projList] = specModule;
  9660. }
  9661. return specModule;
  9662. }
  9663. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  9664. {
  9665. if (IsSkippingExtraResolveChecks())
  9666. return BfIRValue();
  9667. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  9668. {
  9669. //BF_ASSERT(!methodInstance->mIRFunction);
  9670. return BfIRValue();
  9671. }
  9672. auto methodDef = methodInstance->mMethodDef;
  9673. StringT<4096> methodName;
  9674. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  9675. if (isInlined != methodInstance->mAlwaysInline)
  9676. {
  9677. if (isInlined)
  9678. methodName += "__INLINE";
  9679. else
  9680. methodName += "__NOINLINE";
  9681. }
  9682. if (tryExisting)
  9683. {
  9684. auto func = mBfIRBuilder->GetFunction(methodName);
  9685. if (func)
  9686. return func;
  9687. }
  9688. auto intrinsic = GetIntrinsic(methodInstance);
  9689. if (intrinsic)
  9690. return intrinsic;
  9691. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  9692. {
  9693. return CreateDllImportGlobalVar(methodInstance, false);
  9694. }
  9695. BfIRType returnType;
  9696. SizedArray<BfIRType, 8> paramTypes;
  9697. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  9698. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  9699. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  9700. auto callingConv = GetIRCallingConvention(methodInstance);
  9701. if (callingConv != BfIRCallingConv_CDecl)
  9702. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  9703. SetupIRMethod(methodInstance, func, isInlined);
  9704. // auto srcModule = methodInstance->GetOwner()->GetModule();
  9705. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  9706. // {
  9707. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  9708. // {
  9709. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  9710. // }
  9711. // }
  9712. return func;
  9713. }
  9714. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  9715. {
  9716. if (assertName != NULL)
  9717. {
  9718. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9719. }
  9720. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9721. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9722. return BfModuleMethodInstance();
  9723. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9724. BfMethodDef* methodDef = NULL;
  9725. BfTypeInstance* foreignType = NULL;
  9726. if (methodInstance != NULL)
  9727. {
  9728. methodDef = methodInstance->mMethodDef;
  9729. if (methodInstance->mMethodInfoEx != NULL)
  9730. foreignType = methodInstance->mMethodInfoEx->mForeignType;
  9731. }
  9732. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  9733. {
  9734. // Can't use it, not reified
  9735. methodInstance = NULL;
  9736. }
  9737. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  9738. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  9739. {
  9740. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  9741. return BfModuleMethodInstance(methodInstance, func);
  9742. }
  9743. if (foreignType != NULL)
  9744. return GetMethodInstance(typeInstance, methodDef, BfTypeVector(), (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef), foreignType);
  9745. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  9746. }
  9747. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9748. {
  9749. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9750. while (typeInstance != NULL)
  9751. {
  9752. typeInstance->mTypeDef->PopulateMemberSets();
  9753. BfMemberSetEntry* entry = NULL;
  9754. BfMethodDef* methodDef = NULL;
  9755. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9756. methodDef = (BfMethodDef*)entry->mMemberDef;
  9757. while (methodDef != NULL)
  9758. {
  9759. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9760. (methodDef->mGenericParams.size() == 0) &&
  9761. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9762. {
  9763. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9764. if (moduleMethodInstance)
  9765. return moduleMethodInstance;
  9766. }
  9767. methodDef = methodDef->mNextWithSameName;
  9768. }
  9769. if (!checkBase)
  9770. break;
  9771. typeInstance = typeInstance->mBaseType;
  9772. }
  9773. return BfModuleMethodInstance();
  9774. }
  9775. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  9776. {
  9777. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9778. while (typeInstance != NULL)
  9779. {
  9780. typeInstance->mTypeDef->PopulateMemberSets();
  9781. BfMemberSetEntry* entry = NULL;
  9782. BfMethodDef* methodDef = NULL;
  9783. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9784. methodDef = (BfMethodDef*)entry->mMemberDef;
  9785. while (methodDef != NULL)
  9786. {
  9787. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9788. (methodDef->mGenericParams.size() == 0) &&
  9789. (paramTypes.size() == methodDef->mParams.size()))
  9790. {
  9791. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9792. if (moduleMethodInstance.mMethodInstance != NULL)
  9793. {
  9794. bool matches = true;
  9795. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  9796. {
  9797. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  9798. matches = false;
  9799. }
  9800. if (matches)
  9801. return moduleMethodInstance;
  9802. }
  9803. }
  9804. methodDef = methodDef->mNextWithSameName;
  9805. }
  9806. if (!checkBase)
  9807. break;
  9808. typeInstance = typeInstance->mBaseType;
  9809. }
  9810. return BfModuleMethodInstance();
  9811. }
  9812. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  9813. {
  9814. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  9815. PopulateType(internalType);
  9816. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  9817. if (!moduleMethodInstance)
  9818. {
  9819. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  9820. }
  9821. return moduleMethodInstance;
  9822. }
  9823. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  9824. {
  9825. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  9826. typeInstance->mOperatorInfo.Add(NULL);
  9827. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  9828. {
  9829. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  9830. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  9831. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  9832. BfTypeState typeState;
  9833. typeState.mType = typeInstance;
  9834. typeState.mCurTypeDef = operatorDef->mDeclaringType;
  9835. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  9836. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  9837. if (operatorDef->mReturnTypeRef != NULL)
  9838. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  9839. if (operatorDef->mParams.size() >= 1)
  9840. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  9841. if (operatorDef->mParams.size() >= 2)
  9842. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  9843. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  9844. }
  9845. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  9846. }
  9847. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  9848. {
  9849. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  9850. if (operatorInfo == NULL)
  9851. return NULL;
  9852. if (operatorInfo->mReturnType == NULL)
  9853. return NULL;
  9854. auto castFlags = BfCastFlags_IsConstraintCheck;
  9855. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9856. castFlags = (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator);
  9857. if (lhs)
  9858. {
  9859. if (operatorInfo->mLHSType == NULL)
  9860. return NULL;
  9861. if (!CanCast(lhs, operatorInfo->mLHSType, castFlags))
  9862. return NULL;
  9863. }
  9864. if (rhs)
  9865. {
  9866. if (operatorInfo->mRHSType == NULL)
  9867. return NULL;
  9868. if (!CanCast(rhs, operatorInfo->mRHSType, castFlags))
  9869. return NULL;
  9870. }
  9871. return operatorInfo->mReturnType;
  9872. }
  9873. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9874. {
  9875. while (typeInstance != NULL)
  9876. {
  9877. typeInstance->mTypeDef->PopulateMemberSets();
  9878. BfMemberSetEntry* entry = NULL;
  9879. BfMethodDef* methodDef = NULL;
  9880. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9881. methodDef = (BfMethodDef*)entry->mMemberDef;
  9882. while (methodDef != NULL)
  9883. {
  9884. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9885. (methodDef->mGenericParams.size() == 0) &&
  9886. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9887. {
  9888. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  9889. if (!methodInstanceGroup.IsImplemented())
  9890. return false;
  9891. if (methodInstanceGroup.mDefault == NULL)
  9892. return false;
  9893. return methodInstanceGroup.mDefault->mIsReified;
  9894. }
  9895. methodDef = methodDef->mNextWithSameName;
  9896. }
  9897. if (!checkBase)
  9898. break;
  9899. typeInstance = typeInstance->mBaseType;
  9900. }
  9901. return false;
  9902. }
  9903. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9904. {
  9905. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9906. while (typeInstance != NULL)
  9907. {
  9908. typeInstance->mTypeDef->PopulateMemberSets();
  9909. BfMemberSetEntry* entry = NULL;
  9910. BfMethodDef* methodDef = NULL;
  9911. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9912. methodDef = (BfMethodDef*)entry->mMemberDef;
  9913. while (methodDef != NULL)
  9914. {
  9915. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  9916. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9917. return true;
  9918. methodDef = methodDef->mNextWithSameName;
  9919. }
  9920. if (!checkBase)
  9921. break;
  9922. typeInstance = typeInstance->mBaseType;
  9923. }
  9924. return BfModuleMethodInstance();
  9925. }
  9926. String BfModule::FieldToString(BfFieldInstance* fieldInstance)
  9927. {
  9928. auto result = TypeToString(fieldInstance->mOwner);
  9929. result += ".";
  9930. auto fieldDef = fieldInstance->GetFieldDef();
  9931. if (fieldDef != NULL)
  9932. result += fieldDef->mName;
  9933. else
  9934. result += "???";
  9935. return result;
  9936. }
  9937. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* typeGenericArgs, BfTypeVector* methodGenericArgs)
  9938. {
  9939. auto methodDef = methodInst->mMethodDef;
  9940. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  9941. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9942. bool hasGenericArgs = (typeGenericArgs != NULL) || (methodGenericArgs != NULL);
  9943. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  9944. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9945. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  9946. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  9947. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9948. if (allowResolveGenericParamNames)
  9949. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9950. StringT<128> methodName;
  9951. auto _AddTypeName = [&](BfType* type)
  9952. {
  9953. auto typeNameFlags = BfTypeNameFlags_None;
  9954. if (allowResolveGenericParamNames)
  9955. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9956. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9957. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  9958. methodName += TypeToString(type, typeNameFlags);
  9959. };
  9960. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  9961. {
  9962. _AddTypeName(methodInst->mReturnType);
  9963. methodName += " ";
  9964. }
  9965. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  9966. {
  9967. methodName += TypeToString(type, typeNameFlags);
  9968. if (methodName == "$")
  9969. methodName = "";
  9970. else if (!methodName.IsEmpty())
  9971. methodName += ".";
  9972. }
  9973. String accessorString;
  9974. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  9975. if (methodInst->mMethodDef->mIsLocalMethod)
  9976. {
  9977. int atPos = (int)methodDefName.IndexOf('$');
  9978. methodDefName.RemoveToEnd(atPos);
  9979. methodDefName.Replace("@", ".");
  9980. }
  9981. else
  9982. {
  9983. int atPos = (int)methodDefName.IndexOf('$');
  9984. if (atPos != -1)
  9985. {
  9986. accessorString = methodDefName.Substring(0, atPos);
  9987. if ((accessorString == "get") || (accessorString == "set"))
  9988. {
  9989. methodDefName = methodDefName.Substring(atPos + 1);
  9990. }
  9991. else
  9992. accessorString = "";
  9993. }
  9994. }
  9995. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  9996. {
  9997. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9998. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9999. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10000. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  10001. methodName += ".";
  10002. }
  10003. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  10004. {
  10005. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10006. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10007. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10008. methodName += "[";
  10009. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  10010. methodName += "].";
  10011. }
  10012. if (methodDef->mMethodType == BfMethodType_Operator)
  10013. {
  10014. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  10015. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  10016. {
  10017. // Don't add explicit/implicit part, since that's not available in GCC mangling
  10018. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  10019. {
  10020. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  10021. methodName += "explicit ";
  10022. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  10023. methodName += "explicit ";
  10024. }*/
  10025. methodName += "operator ";
  10026. if (methodInst->mReturnType != NULL)
  10027. methodName += TypeToString(methodInst->mReturnType);
  10028. }
  10029. else
  10030. {
  10031. methodName += "operator";
  10032. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  10033. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  10034. }
  10035. }
  10036. else if (methodDef->mMethodType == BfMethodType_Ctor)
  10037. {
  10038. if (methodDef->mIsStatic)
  10039. methodName += "__BfStaticCtor";
  10040. else
  10041. methodName += "this";
  10042. accessorString = "";
  10043. }
  10044. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  10045. {
  10046. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10047. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10048. {
  10049. methodName += "get indexer";
  10050. }
  10051. else
  10052. {
  10053. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10054. propertyDecl->mNameNode->ToString(methodName);
  10055. methodName += " get accessor";
  10056. return methodName;
  10057. }
  10058. }
  10059. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10060. {
  10061. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10062. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10063. {
  10064. methodName += "set indexer";
  10065. }
  10066. else
  10067. {
  10068. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10069. propertyDecl->mNameNode->ToString(methodName);
  10070. methodName += " set accessor";
  10071. return methodName;
  10072. }
  10073. }
  10074. else
  10075. methodName += methodDefName;
  10076. if (methodDef->mMethodType == BfMethodType_Mixin)
  10077. methodName += "!";
  10078. BfTypeVector newMethodGenericArgs;
  10079. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  10080. {
  10081. methodName += "<";
  10082. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  10083. {
  10084. if (i > 0)
  10085. methodName += ", ";
  10086. BfTypeNameFlags typeNameFlags = BfTypeNameFlag_ShortConst;
  10087. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  10088. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10089. if (allowResolveGenericParamNames)
  10090. typeNameFlags = (BfTypeNameFlags)(typeNameFlags | BfTypeNameFlag_ResolveGenericParamNames);
  10091. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  10092. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  10093. {
  10094. bool hasEmpty = false;
  10095. for (auto arg : *methodGenericArgs)
  10096. {
  10097. if (arg == NULL)
  10098. hasEmpty = true;
  10099. }
  10100. if (hasEmpty)
  10101. {
  10102. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  10103. {
  10104. auto arg = (*methodGenericArgs)[genericIdx];
  10105. if (arg != NULL)
  10106. newMethodGenericArgs.push_back(arg);
  10107. else
  10108. {
  10109. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  10110. if (genericParamInst->mTypeConstraint != NULL)
  10111. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  10112. else
  10113. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  10114. }
  10115. }
  10116. methodGenericArgs = &newMethodGenericArgs;
  10117. }
  10118. if (type->IsUnspecializedType())
  10119. type = ResolveGenericType(type, NULL, methodGenericArgs, mCurTypeInstance);
  10120. }
  10121. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  10122. {
  10123. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  10124. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  10125. methodName += TypeToString(type, typeNameFlags);
  10126. }
  10127. else
  10128. methodName += TypeToString(type, typeNameFlags);
  10129. }
  10130. methodName += ">";
  10131. }
  10132. if (accessorString.length() == 0)
  10133. {
  10134. int dispParamIdx = 0;
  10135. methodName += "(";
  10136. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  10137. {
  10138. int paramKind = methodInst->GetParamKind(paramIdx);
  10139. if ((paramKind == BfParamKind_ImplicitCapture) || (paramKind == BfParamKind_AppendIdx))
  10140. continue;
  10141. if (dispParamIdx > 0)
  10142. methodName += ", ";
  10143. if (paramKind == BfParamKind_Params)
  10144. methodName += "params ";
  10145. BfType* type = methodInst->GetParamType(paramIdx);
  10146. _AddTypeName(type);
  10147. methodName += " ";
  10148. methodName += methodInst->GetParamName(paramIdx);
  10149. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  10150. if ((paramInitializer != NULL) && ((methodNameFlags & BfMethodNameFlag_NoAst) == 0))
  10151. {
  10152. methodName += " = ";
  10153. methodName += paramInitializer->ToString();
  10154. }
  10155. dispParamIdx++;
  10156. }
  10157. methodName += ")";
  10158. }
  10159. if (accessorString.length() != 0)
  10160. {
  10161. methodName += " ";
  10162. methodName += accessorString;
  10163. }
  10164. if ((methodNameFlags & BfMethodNameFlag_IncludeMut) != 0)
  10165. {
  10166. if ((methodDef->mIsMutating) && (methodInst->GetOwner()->IsValueType()))
  10167. methodName += " mut";
  10168. }
  10169. return methodName;
  10170. }
  10171. void BfModule::pt(BfType* type)
  10172. {
  10173. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  10174. }
  10175. void BfModule::pm(BfMethodInstance* type)
  10176. {
  10177. OutputDebugStrF("%s\n", MethodToString(type).c_str());
  10178. }
  10179. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  10180. {
  10181. if ((flagsLeft & checkFlag) == 0)
  10182. return;
  10183. if (!str.empty())
  10184. {
  10185. if (flagsLeft == checkFlag)
  10186. {
  10187. if ((int)str.IndexOf(',') != -1)
  10188. str += ", and ";
  10189. else
  10190. str += " and ";
  10191. }
  10192. else
  10193. str += ", ";
  10194. }
  10195. str += addString;
  10196. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  10197. }
  10198. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  10199. {
  10200. String resultStr;
  10201. auto flagsLeft = attrTarget;
  10202. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  10203. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  10204. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  10205. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  10206. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  10207. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  10208. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  10209. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  10210. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  10211. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  10212. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  10213. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  10214. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  10215. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  10216. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  10217. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  10218. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  10219. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  10220. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  10221. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  10222. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  10223. if (resultStr.IsEmpty())
  10224. return "<nothing>";
  10225. return resultStr;
  10226. }
  10227. BfIRType BfModule::CurrentAddToConstHolder(BfIRType irType)
  10228. {
  10229. if (irType.mKind == BfIRTypeData::TypeKind_SizedArray)
  10230. {
  10231. auto sizedArrayType = (BfConstantSizedArrayType*)mBfIRBuilder->GetConstantById(irType.mId);
  10232. return mCurTypeInstance->GetOrCreateConstHolder()->GetSizedArrayType(CurrentAddToConstHolder(sizedArrayType->mType), (int)sizedArrayType->mLength);
  10233. }
  10234. return irType;
  10235. }
  10236. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  10237. {
  10238. auto constant = mBfIRBuilder->GetConstant(irVal);
  10239. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  10240. if (stringPoolIdx != -1)
  10241. {
  10242. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  10243. return;
  10244. }
  10245. if (constant->mConstType == BfConstType_Agg)
  10246. {
  10247. auto constArray = (BfConstantAgg*)constant;
  10248. SizedArray<BfIRValue, 8> newVals;
  10249. for (auto val : constArray->mValues)
  10250. {
  10251. auto newVal = val;
  10252. CurrentAddToConstHolder(newVal);
  10253. newVals.push_back(newVal);
  10254. }
  10255. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstAgg(CurrentAddToConstHolder(constArray->mType), newVals);
  10256. return;
  10257. }
  10258. auto origConst = irVal;
  10259. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10260. {
  10261. auto bitcast = (BfConstantBitCast*)constant;
  10262. BfIRValue newVal;
  10263. if (constant->mConstType == BfConstType_BitCast)
  10264. {
  10265. newVal = BfIRValue(BfIRValueFlags_Const, bitcast->mTarget);
  10266. CurrentAddToConstHolder(newVal);
  10267. }
  10268. else
  10269. newVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstNull();
  10270. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstBitCast(newVal, CurrentAddToConstHolder(bitcast->mToType));
  10271. return;
  10272. }
  10273. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  10274. }
  10275. void BfModule::ClearConstData()
  10276. {
  10277. mBfIRBuilder->ClearConstData();
  10278. mStringObjectPool.Clear();
  10279. mStringCharPtrPool.Clear();
  10280. mStringPoolRefs.Clear();
  10281. mUnreifiedStringPoolRefs.Clear();
  10282. mStaticFieldRefs.Clear();
  10283. }
  10284. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  10285. {
  10286. switch (constant->mTypeCode)
  10287. {
  10288. case BfTypeCode_StringId:
  10289. case BfTypeCode_Boolean:
  10290. case BfTypeCode_Int8:
  10291. case BfTypeCode_UInt8:
  10292. case BfTypeCode_Int16:
  10293. case BfTypeCode_UInt16:
  10294. case BfTypeCode_Int32:
  10295. case BfTypeCode_UInt32:
  10296. case BfTypeCode_Int64:
  10297. case BfTypeCode_UInt64:
  10298. case BfTypeCode_IntPtr:
  10299. case BfTypeCode_UIntPtr:
  10300. case BfTypeCode_IntUnknown:
  10301. case BfTypeCode_UIntUnknown:
  10302. case BfTypeCode_Char8:
  10303. case BfTypeCode_Char16:
  10304. case BfTypeCode_Char32:
  10305. case BfTypeCode_Float:
  10306. case BfTypeCode_Double:
  10307. {
  10308. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10309. BfTypedValue typedValue;
  10310. bool allowUnactualized = mBfIRBuilder->mIgnoreWrites;
  10311. if (constant->mTypeCode == BfTypeCode_StringId)
  10312. {
  10313. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10314. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10315. {
  10316. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType, allowUnactualized), wantType);
  10317. return typedValue;
  10318. }
  10319. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  10320. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType, allowUnactualized), stringType);
  10321. }
  10322. if (!typedValue)
  10323. {
  10324. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10325. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  10326. }
  10327. if (typedValue.mType == wantType)
  10328. return typedValue;
  10329. if (wantType->IsTypedPrimitive())
  10330. {
  10331. if (typedValue.mType == wantType->GetUnderlyingType())
  10332. {
  10333. typedValue.mType = wantType;
  10334. return typedValue;
  10335. }
  10336. }
  10337. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  10338. if (!castedTypedValue)
  10339. return BfTypedValue();
  10340. return castedTypedValue;
  10341. }
  10342. break;
  10343. default: break;
  10344. }
  10345. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  10346. BF_ASSERT(irValue);
  10347. if (!irValue)
  10348. return BfTypedValue();
  10349. if (constant->mConstType == BfConstType_GlobalVar)
  10350. {
  10351. mBfIRBuilder->PopulateType(wantType);
  10352. auto result = BfTypedValue(irValue, wantType, true);
  10353. if (!wantType->IsComposite())
  10354. result = LoadValue(result);
  10355. return result;
  10356. }
  10357. return BfTypedValue(irValue, wantType, false);
  10358. }
  10359. bool BfModule::HasUnactializedConstant(BfConstant* constant, BfIRConstHolder* constHolder)
  10360. {
  10361. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  10362. return true;
  10363. if (constant->mTypeCode == BfTypeCode_StringId)
  10364. return true;
  10365. if (constant->mConstType == BfConstType_Agg)
  10366. {
  10367. auto constArray = (BfConstantAgg*)constant;
  10368. for (auto val : constArray->mValues)
  10369. {
  10370. if (HasUnactializedConstant(constHolder->GetConstant(val), constHolder))
  10371. return true;
  10372. }
  10373. }
  10374. return false;
  10375. }
  10376. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType, bool allowUnactualized)
  10377. {
  10378. if (constant->mTypeCode == BfTypeCode_NullPtr)
  10379. {
  10380. if ((wantType == NULL) && (constant->mIRType.mKind == BfIRTypeData::TypeKind_TypeId))
  10381. wantType = mContext->mTypes[constant->mIRType.mId];
  10382. if (wantType == NULL)
  10383. return mBfIRBuilder->CreateConstNull();
  10384. return GetDefaultValue(wantType);
  10385. }
  10386. if (constant->mTypeCode == BfTypeCode_StringId)
  10387. {
  10388. if (!allowUnactualized)
  10389. {
  10390. if ((wantType == NULL) ||
  10391. (wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10392. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10393. {
  10394. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  10395. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  10396. if ((wantType != NULL) && (wantType->IsPointer()))
  10397. return GetStringCharPtr(stringObjConst, true);
  10398. return stringObjConst;
  10399. }
  10400. }
  10401. }
  10402. if (constant->mConstType == Beefy::BfConstType_TypeOf)
  10403. {
  10404. auto constTypeOf = (BfTypeOf_Const*)constant;
  10405. if (mCurTypeInstance != NULL)
  10406. AddDependency(constTypeOf->mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10407. return CreateTypeDataRef(constTypeOf->mType);
  10408. }
  10409. if (constant->mConstType == BfConstType_PtrToInt)
  10410. {
  10411. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  10412. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10413. return mBfIRBuilder->CreatePtrToInt(ConstantToCurrent(fromTarget, constHolder, NULL), fromPtrToInt->mToTypeCode);
  10414. }
  10415. if (constant->mConstType == BfConstType_IntToPtr)
  10416. {
  10417. auto fromPtrToInt = (BfConstantIntToPtr*)constant;
  10418. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10419. BfIRType toIRType = fromPtrToInt->mToType;
  10420. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10421. {
  10422. auto toType = mContext->mTypes[toIRType.mId];
  10423. toIRType = mBfIRBuilder->MapType(toType);
  10424. }
  10425. return mBfIRBuilder->CreateIntToPtr(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10426. }
  10427. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10428. {
  10429. auto bitcast = (BfConstantBitCast*)constant;
  10430. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  10431. BfIRType toIRType = bitcast->mToType;
  10432. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10433. {
  10434. auto toType = mContext->mTypes[toIRType.mId];
  10435. toIRType = mBfIRBuilder->MapType(toType);
  10436. }
  10437. return mBfIRBuilder->CreateBitCast(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10438. }
  10439. if (constant->mConstType == BfConstType_Agg)
  10440. {
  10441. auto constArray = (BfConstantAgg*)constant;
  10442. if ((wantType == NULL) && (constArray->mType.mKind == BfIRTypeData::TypeKind_TypeId))
  10443. wantType = mContext->mTypes[constArray->mType.mId];
  10444. if (wantType->IsArray())
  10445. wantType = CreateSizedArrayType(wantType->GetUnderlyingType(), (int)constArray->mValues.mSize);
  10446. bool handleAsArray = false;
  10447. SizedArray<BfIRValue, 8> newVals;
  10448. if (wantType->IsSizedArray())
  10449. {
  10450. handleAsArray = true;
  10451. }
  10452. else if (wantType->IsInstanceOf(mCompiler->mSpanTypeDef))
  10453. {
  10454. auto valueType = ResolveTypeDef(mCompiler->mValueTypeTypeDef);
  10455. handleAsArray = true;
  10456. if (!constArray->mValues.IsEmpty())
  10457. {
  10458. auto firstConstant = constHolder->GetConstant(constArray->mValues[0]);
  10459. if ((firstConstant->mConstType == BfConstType_AggZero) && (firstConstant->mIRType.mKind == BfIRType::TypeKind_TypeId) &&
  10460. (firstConstant->mIRType.mId == valueType->mTypeId))
  10461. handleAsArray = false;
  10462. if (firstConstant->mConstType == BfConstType_Agg)
  10463. {
  10464. auto firstConstArray = (BfConstantAgg*)firstConstant;
  10465. if ((firstConstArray->mType.mKind == BfIRType::TypeKind_TypeId) &&
  10466. (firstConstArray->mType.mId == valueType->mTypeId))
  10467. handleAsArray = false;
  10468. }
  10469. }
  10470. }
  10471. if (handleAsArray)
  10472. {
  10473. auto elementType = wantType->GetUnderlyingType();
  10474. for (auto val : constArray->mValues)
  10475. {
  10476. newVals.Add(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  10477. }
  10478. }
  10479. else
  10480. {
  10481. auto wantTypeInst = wantType->ToTypeInstance();
  10482. if (wantTypeInst == NULL)
  10483. {
  10484. InternalError("BfModule::ConstantToCurrent typeInst error");
  10485. return BfIRValue();
  10486. }
  10487. if (wantTypeInst->mBaseType != NULL)
  10488. {
  10489. auto baseVal = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[0]), constHolder, wantTypeInst->mBaseType);
  10490. newVals.Add(baseVal);
  10491. }
  10492. if (wantType->IsUnion())
  10493. {
  10494. auto innerType = wantType->ToTypeInstance()->GetUnionInnerType();
  10495. if (!innerType->IsValuelessType())
  10496. {
  10497. auto val = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[1]), constHolder, innerType);
  10498. newVals.Add(val);
  10499. }
  10500. }
  10501. if ((!wantType->IsUnion()) || (wantType->IsPayloadEnum()))
  10502. {
  10503. for (auto& fieldInstance : wantTypeInst->mFieldInstances)
  10504. {
  10505. if (fieldInstance.mDataIdx < 0)
  10506. continue;
  10507. if (fieldInstance.mDataIdx >= constArray->mValues.mSize)
  10508. {
  10509. InternalError("BfModule::ConstantToCurrent union error");
  10510. return BfIRValue();
  10511. }
  10512. auto val = constArray->mValues[fieldInstance.mDataIdx];
  10513. BfIRValue memberVal = ConstantToCurrent(constHolder->GetConstant(val), constHolder, fieldInstance.mResolvedType);
  10514. if (fieldInstance.mDataIdx == newVals.mSize)
  10515. newVals.Add(memberVal);
  10516. else
  10517. {
  10518. while (fieldInstance.mDataIdx >= newVals.mSize)
  10519. newVals.Add(BfIRValue());
  10520. newVals[fieldInstance.mDataIdx] = memberVal;
  10521. }
  10522. }
  10523. }
  10524. for (auto& val : newVals)
  10525. {
  10526. if (!val)
  10527. val = mBfIRBuilder->CreateConstArrayZero(0);
  10528. }
  10529. }
  10530. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(wantType, BfIRPopulateType_Identity), newVals);
  10531. }
  10532. return mBfIRBuilder->CreateConst(constant, constHolder);
  10533. }
  10534. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget, bool force)
  10535. {
  10536. if (attrTarget == BfAttributeTargets_SkipValidate)
  10537. return;
  10538. for (auto& customAttribute : customAttributes->mAttributes)
  10539. {
  10540. if (!customAttribute.mAwaitingValidation)
  10541. continue;
  10542. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  10543. {
  10544. if ((customAttribute.mIsMultiUse) && (!force))
  10545. continue;
  10546. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  10547. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  10548. }
  10549. customAttribute.mAwaitingValidation = false;
  10550. }
  10551. }
  10552. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10553. {
  10554. bool allowNonConstArgs = (flags & BfGetCustomAttributesFlags_AllowNonConstArgs) != 0;
  10555. bool keepConstsInModule = (flags & BfGetCustomAttributesFlags_KeepConstsInModule) != 0;
  10556. if (!mCompiler->mHasRequiredTypes)
  10557. return;
  10558. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  10559. {
  10560. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  10561. sourceClassifier->VisitChild(attributesDirective);
  10562. }
  10563. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  10564. if (mCompiler->IsAutocomplete())
  10565. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  10566. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  10567. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  10568. BfTypeDef* activeTypeDef = GetActiveTypeDef();
  10569. BfAutoComplete* autoComplete = NULL;
  10570. if (mCompiler->mResolvePassData != NULL)
  10571. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  10572. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  10573. {
  10574. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  10575. {
  10576. if (captureInfo == NULL)
  10577. {
  10578. Fail("Capture specifiers can only be used in lambda allocations", tokenNode);
  10579. continue;
  10580. }
  10581. BfCaptureInfo::Entry captureEntry;
  10582. captureEntry.mRefNode = tokenNode;
  10583. captureEntry.mCaptureType = BfCaptureType_Copy;
  10584. if (tokenNode->mToken == BfToken_Ampersand)
  10585. captureEntry.mCaptureType = BfCaptureType_Reference;
  10586. if (tokenNode->mToken == BfToken_Question)
  10587. captureEntry.mCaptureType = BfCaptureType_Auto;
  10588. if (!attributesDirective->mArguments.IsEmpty())
  10589. {
  10590. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]))
  10591. captureEntry.mNameNode = identifierNode;
  10592. else if (auto thisExpr = BfNodeDynCast<BfThisExpression>(attributesDirective->mArguments[0]))
  10593. {
  10594. captureEntry.mNameNode = thisExpr;
  10595. }
  10596. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  10597. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  10598. }
  10599. captureInfo->mCaptures.Add(captureEntry);
  10600. continue;
  10601. }
  10602. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  10603. BfCustomAttribute customAttribute;
  10604. customAttribute.mAwaitingValidation = true;
  10605. customAttribute.mDeclaringType = activeTypeDef;
  10606. customAttribute.mRef = attributesDirective;
  10607. customAttribute.mIsMultiUse = attributesDirective->mIsMultiUse;
  10608. if (attributesDirective->mAttrOpenToken != NULL)
  10609. targetOverride = (BfAttributeTargets)0;
  10610. if (attributesDirective->mAttributeTypeRef == NULL)
  10611. {
  10612. AssertErrorState();
  10613. continue;
  10614. }
  10615. BfType* attrType;
  10616. if (mContext->mCurTypeState != NULL)
  10617. {
  10618. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10619. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10620. }
  10621. else
  10622. {
  10623. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10624. }
  10625. BfTypeDef* attrTypeDef = NULL;
  10626. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  10627. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  10628. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10629. {
  10630. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  10631. if (attrTypeDef != NULL)
  10632. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  10633. }
  10634. bool isBypassedAttr = false;
  10635. if (attrTypeDef != NULL)
  10636. {
  10637. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  10638. // We solve it by having a 'bypass' for known attributes that Object depends on
  10639. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  10640. {
  10641. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  10642. {
  10643. for (auto methodDef : attrTypeDef->mMethods)
  10644. {
  10645. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  10646. {
  10647. customAttribute.mType = attrType->ToTypeInstance();
  10648. customAttribute.mCtor = methodDef;
  10649. isBypassedAttr = true;
  10650. break;
  10651. }
  10652. }
  10653. }
  10654. }
  10655. if (isBypassedAttr)
  10656. {
  10657. customAttribute.mAwaitingValidation = false;
  10658. customAttributes->mAttributes.push_back(customAttribute);
  10659. continue;
  10660. }
  10661. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInst(mContext->mUnreifiedModule->mCurTypeInstance, mCurTypeInstance);
  10662. SetAndRestoreValue<BfMethodInstance*> prevCurMethodInst(mContext->mUnreifiedModule->mCurMethodInstance, mCurMethodInstance);
  10663. if (mContext->mCurTypeState != NULL)
  10664. {
  10665. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10666. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10667. }
  10668. else
  10669. {
  10670. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10671. }
  10672. }
  10673. BfTypeInstance* attrTypeInst = NULL;
  10674. if (attrType == NULL)
  10675. continue;
  10676. attrTypeInst = attrType->ToTypeInstance();
  10677. if ((attrTypeInst != NULL) && (attrTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting))
  10678. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  10679. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  10680. {
  10681. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  10682. continue;
  10683. }
  10684. if ((mIsReified) && (attrTypeInst->mAttributeData != NULL) && ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_ReflectAttribute) != 0))
  10685. {
  10686. // Reify attribute
  10687. PopulateType(attrTypeInst);
  10688. }
  10689. if (mCurTypeInstance != NULL)
  10690. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10691. customAttribute.mType = attrTypeInst;
  10692. bool allocatedMethodState = NULL;
  10693. defer(
  10694. {
  10695. if (allocatedMethodState)
  10696. {
  10697. delete mCurMethodState;
  10698. mCurMethodState = NULL;
  10699. }
  10700. });
  10701. if (mCurMethodState == NULL)
  10702. {
  10703. allocatedMethodState = true;
  10704. mCurMethodState = new BfMethodState();
  10705. mCurMethodState->mTempKind = BfMethodState::TempKind_Static;
  10706. }
  10707. BfConstResolver constResolver(this);
  10708. if (allowNonConstArgs)
  10709. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  10710. bool inPropSet = false;
  10711. SizedArray<BfResolvedArg, 2> argValues;
  10712. for (BfExpression* arg : attributesDirective->mArguments)
  10713. {
  10714. if (arg == NULL)
  10715. {
  10716. continue;
  10717. }
  10718. if (autoComplete != NULL)
  10719. autoComplete->mShowAttributeProperties = attrTypeInst;
  10720. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  10721. {
  10722. inPropSet = true;
  10723. if (autoComplete != NULL)
  10724. autoComplete->CheckNode(assignExpr->mLeft, true);
  10725. String findName = assignExpr->mLeft->ToString();
  10726. BfPropertyDef* bestProp = NULL;
  10727. BfTypeInstance* bestPropTypeInst = NULL;
  10728. BfFieldDef* bestField = NULL;
  10729. BfTypeInstance* bestFieldTypeInst = NULL;
  10730. auto checkTypeInst = attrTypeInst;
  10731. while (checkTypeInst != NULL)
  10732. {
  10733. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  10734. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  10735. {
  10736. if (prop->mName == findName)
  10737. {
  10738. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  10739. {
  10740. bestProp = prop;
  10741. bestPropTypeInst = checkTypeInst;
  10742. }
  10743. }
  10744. }
  10745. for (auto field : checkTypeInst->mTypeDef->mFields)
  10746. {
  10747. if (field->mName == findName)
  10748. {
  10749. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  10750. {
  10751. bestField = field;
  10752. bestFieldTypeInst = checkTypeInst;
  10753. }
  10754. }
  10755. }
  10756. if ((bestProp != NULL) || (bestField != NULL))
  10757. break;
  10758. checkTypeInst = checkTypeInst->mBaseType;
  10759. }
  10760. bool handledExpr = false;
  10761. if (bestField != NULL)
  10762. {
  10763. handledExpr = true;
  10764. if (mCompiler->mResolvePassData != NULL)
  10765. {
  10766. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  10767. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10768. {
  10769. autoComplete->mDefField = bestField;
  10770. autoComplete->mDefType = attrTypeDef;
  10771. }
  10772. }
  10773. if (bestField->mProtection != BfProtection_Public)
  10774. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10775. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10776. BfCustomAttributeSetField setField;
  10777. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  10778. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  10779. if (assignExpr->mRight != NULL)
  10780. {
  10781. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType, BfConstResolveFlag_NoActualizeValues);
  10782. if (result)
  10783. {
  10784. if (!keepConstsInModule)
  10785. CurrentAddToConstHolder(result.mValue);
  10786. setField.mParam = result;
  10787. customAttribute.mSetField.push_back(setField);
  10788. }
  10789. }
  10790. }
  10791. else if (bestProp == NULL)
  10792. {
  10793. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  10794. }
  10795. else
  10796. {
  10797. BfMethodDef* setMethod = NULL;
  10798. for (auto methodDef : bestProp->mMethods)
  10799. {
  10800. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10801. {
  10802. setMethod = methodDef;
  10803. break;
  10804. }
  10805. }
  10806. if (setMethod == NULL)
  10807. {
  10808. Fail("Property has no setter", assignExpr->mLeft);
  10809. }
  10810. else
  10811. {
  10812. if (mCompiler->mResolvePassData != NULL)
  10813. {
  10814. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  10815. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10816. {
  10817. autoComplete->mDefProp = bestProp;
  10818. autoComplete->mDefType = attrTypeDef;
  10819. }
  10820. }
  10821. handledExpr = true;
  10822. if (bestProp->mProtection != BfProtection_Public)
  10823. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10824. BfResolvedArg resolvedArg;
  10825. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10826. BfCustomAttributeSetProperty setProperty;
  10827. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  10828. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  10829. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  10830. if (methodInstance.mMethodInstance != NULL)
  10831. {
  10832. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  10833. if (assignExpr->mRight != NULL)
  10834. {
  10835. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType, BfConstResolveFlag_NoActualizeValues);
  10836. if ((result) && (!result.mType->IsVar()))
  10837. {
  10838. if (!result.mValue.IsConst())
  10839. result = GetDefaultTypedValue(result.mType);
  10840. BF_ASSERT(result.mType == propType);
  10841. if (!keepConstsInModule)
  10842. CurrentAddToConstHolder(result.mValue);
  10843. setProperty.mParam = result;
  10844. customAttribute.mSetProperties.push_back(setProperty);
  10845. }
  10846. }
  10847. }
  10848. }
  10849. }
  10850. if ((!handledExpr) && (assignExpr->mRight != NULL))
  10851. constResolver.Resolve(assignExpr->mRight, NULL, BfConstResolveFlag_NoActualizeValues);
  10852. }
  10853. else
  10854. {
  10855. if (inPropSet)
  10856. {
  10857. Fail("Named attribute argument expected", arg); // CS1016
  10858. }
  10859. BfDeferEvalChecker deferEvalChecker;
  10860. arg->Accept(&deferEvalChecker);
  10861. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  10862. BfResolvedArg resolvedArg;
  10863. resolvedArg.mExpression = arg;
  10864. if (deferParamEval)
  10865. {
  10866. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  10867. }
  10868. else
  10869. resolvedArg.mTypedValue = constResolver.Resolve(arg, NULL, BfConstResolveFlag_NoActualizeValues);
  10870. if (!inPropSet)
  10871. {
  10872. argValues.push_back(resolvedArg);
  10873. }
  10874. }
  10875. if (autoComplete != NULL)
  10876. autoComplete->mShowAttributeProperties = NULL;
  10877. }
  10878. auto wasCapturingMethodInfo = false;
  10879. if (autoComplete != NULL)
  10880. {
  10881. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  10882. if (attributesDirective->mCtorOpenParen != NULL)
  10883. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  10884. }
  10885. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, BfMethodGenericArguments());
  10886. methodMatcher.mBfEvalExprFlags = constResolver.mBfEvalExprFlags;
  10887. attrTypeDef = attrTypeInst->mTypeDef;
  10888. bool success = true;
  10889. bool isFailurePass = false;
  10890. for (int pass = 0; pass < 2; pass++)
  10891. {
  10892. bool isFailurePass = pass == 1;
  10893. for (auto checkMethod : attrTypeDef->mMethods)
  10894. {
  10895. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  10896. continue; // Don't match private default ctor if there's a user-defined one
  10897. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  10898. continue;
  10899. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  10900. continue;
  10901. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  10902. }
  10903. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  10904. break;
  10905. }
  10906. if (autoComplete != NULL)
  10907. {
  10908. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  10909. {
  10910. autoComplete->mIsCapturingMethodMatchInfo = true;
  10911. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  10912. }
  10913. else
  10914. autoComplete->mIsCapturingMethodMatchInfo = false;
  10915. }
  10916. if (methodMatcher.mBestMethodDef == NULL)
  10917. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  10918. if (methodMatcher.mBestMethodDef == NULL)
  10919. {
  10920. AssertErrorState();
  10921. continue;
  10922. }
  10923. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  10924. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  10925. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  10926. {
  10927. Fail("Custom attribute circular reference", attributesDirective);
  10928. }
  10929. if (mCurTypeInstance != NULL)
  10930. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10931. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  10932. success = false;
  10933. for (auto& arg : argValues)
  10934. {
  10935. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  10936. {
  10937. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  10938. constResolver.Resolve(expr, NULL, BfConstResolveFlag_NoActualizeValues);
  10939. }
  10940. }
  10941. // Move all those to the constHolder
  10942. if (!keepConstsInModule)
  10943. {
  10944. for (auto& ctorArg : customAttribute.mCtorArgs)
  10945. {
  10946. if (ctorArg.IsConst())
  10947. CurrentAddToConstHolder(ctorArg);
  10948. }
  10949. }
  10950. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  10951. {
  10952. targetOverride = BfAttributeTargets_ReturnValue;
  10953. if (attrTarget != BfAttributeTargets_Method)
  10954. {
  10955. 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.",
  10956. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  10957. success = false;
  10958. }
  10959. }
  10960. if ((success) && (targetOverride != (BfAttributeTargets)0))
  10961. {
  10962. if ((mCurMethodInstance != NULL) && (targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  10963. {
  10964. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  10965. if (methodInfoEx->mMethodCustomAttributes == NULL)
  10966. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  10967. if (success)
  10968. {
  10969. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  10970. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  10971. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  10972. }
  10973. }
  10974. // Mark as failed since we don't actually want to add this to the custom attributes set
  10975. success = false;
  10976. }
  10977. if (success)
  10978. {
  10979. if ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_DisallowAllowMultiple) != 0)
  10980. {
  10981. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  10982. {
  10983. if (prevCustomAttribute.mType == attrTypeInst)
  10984. {
  10985. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToCleanAttributeString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  10986. }
  10987. }
  10988. }
  10989. }
  10990. if (success)
  10991. {
  10992. customAttributes->mAttributes.push_back(customAttribute);
  10993. }
  10994. }
  10995. ValidateCustomAttributes(customAttributes, attrTarget);
  10996. }
  10997. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10998. {
  10999. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  11000. GetCustomAttributes(customAttributes, attributesDirective, attrType, flags, captureInfo);
  11001. return customAttributes;
  11002. }
  11003. BfCustomAttributes* BfModule::GetCustomAttributes(BfTypeDef* typeDef)
  11004. {
  11005. BF_ASSERT(mCompiler->IsAutocomplete());
  11006. BfAttributeTargets attrTarget;
  11007. if (typeDef->mIsDelegate)
  11008. attrTarget = BfAttributeTargets_Delegate;
  11009. else if (typeDef->mIsFunction)
  11010. attrTarget = BfAttributeTargets_Function;
  11011. else if (typeDef->mTypeCode == BfTypeCode_Enum)
  11012. attrTarget = BfAttributeTargets_Enum;
  11013. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  11014. attrTarget = BfAttributeTargets_Interface;
  11015. else if (typeDef->mTypeCode == BfTypeCode_Struct)
  11016. attrTarget = BfAttributeTargets_Struct;
  11017. else if (typeDef->mTypeCode == BfTypeCode_Extension)
  11018. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Struct | BfAttributeTargets_Class | BfAttributeTargets_Interface | BfAttributeTargets_Enum);
  11019. else
  11020. attrTarget = BfAttributeTargets_Class;
  11021. return GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  11022. }
  11023. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  11024. {
  11025. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  11026. Warn(0, "Unused attributes", attributeState->mSrc);
  11027. }
  11028. void BfModule::ProcessTypeInstCustomAttributes(int& packing, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  11029. {
  11030. if (mCurTypeInstance->mTypeDef->mIsAlwaysInclude)
  11031. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11032. if (mCurTypeInstance->mCustomAttributes != NULL)
  11033. {
  11034. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11035. {
  11036. String typeName = TypeToString(customAttribute.mType);
  11037. if (typeName == "System.PackedAttribute")
  11038. {
  11039. packing = 1;
  11040. if (customAttribute.mCtorArgs.size() >= 1)
  11041. {
  11042. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11043. int checkPacking = alignConstant->mInt32;
  11044. if (((checkPacking & (checkPacking - 1)) == 0) && (packing > 0) && (packing < 256))
  11045. packing = checkPacking;
  11046. else
  11047. Fail("Packing must be a power of 2", customAttribute.GetRefNode());
  11048. }
  11049. }
  11050. else if (typeName == "System.UnionAttribute")
  11051. {
  11052. isUnion = true;
  11053. }
  11054. else if (typeName == "System.CReprAttribute")
  11055. {
  11056. isCRepr = true;
  11057. isOrdered = true;
  11058. }
  11059. else if (typeName == "System.OrderedAttribute")
  11060. {
  11061. isOrdered = true;
  11062. }
  11063. else if (typeName == "System.AlwaysIncludeAttribute")
  11064. {
  11065. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11066. for (auto setProp : customAttribute.mSetProperties)
  11067. {
  11068. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  11069. if (propertyDef->mName == "AssumeInstantiated")
  11070. {
  11071. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11072. if ((constant != NULL) && (constant->mBool))
  11073. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_AssumeInstantiated);
  11074. }
  11075. else if (propertyDef->mName == "IncludeAllMethods")
  11076. {
  11077. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11078. if ((constant != NULL) && (constant->mBool))
  11079. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_IncludeAllMethods);
  11080. }
  11081. }
  11082. }
  11083. else if (typeName == "System.AlignAttribute")
  11084. {
  11085. if (customAttribute.mCtorArgs.size() >= 1)
  11086. {
  11087. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11088. int checkAlign = alignConstant->mInt32;
  11089. if ((checkAlign & (checkAlign - 1)) == 0)
  11090. alignOverride = checkAlign;
  11091. else
  11092. Fail("Alignment must be a power of 2", customAttribute.GetRefNode());
  11093. }
  11094. }
  11095. else if (typeName == "System.UnderlyingArrayAttribute")
  11096. {
  11097. if (customAttribute.mCtorArgs.size() >= 2)
  11098. {
  11099. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11100. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  11101. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  11102. {
  11103. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  11104. underlyingArraySize = sizeConstant->mInt32;
  11105. }
  11106. }
  11107. }
  11108. if (customAttribute.mType->mAttributeData == NULL)
  11109. PopulateType(customAttribute.mType);
  11110. BF_ASSERT(customAttribute.mType->mAttributeData != NULL);
  11111. if ((customAttribute.mType->mAttributeData != NULL) && ((customAttribute.mType->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0))
  11112. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | customAttribute.mType->mAttributeData->mAlwaysIncludeUser);
  11113. }
  11114. }
  11115. }
  11116. // Checking to see if we're an attribute or not
  11117. void BfModule::ProcessCustomAttributeData()
  11118. {
  11119. if (mCurTypeInstance->mAttributeData != NULL)
  11120. return;
  11121. bool isAttribute = false;
  11122. auto checkTypeInst = mCurTypeInstance->mBaseType;
  11123. while (checkTypeInst != NULL)
  11124. {
  11125. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  11126. isAttribute = true;
  11127. checkTypeInst = checkTypeInst->mBaseType;
  11128. }
  11129. if (!isAttribute)
  11130. return;
  11131. auto attributeData = new BfAttributeData();
  11132. bool hasCustomAttribute = false;
  11133. if (mCurTypeInstance->mCustomAttributes != NULL)
  11134. {
  11135. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11136. {
  11137. if (customAttribute.mType->IsInstanceOf(mCompiler->mAttributeUsageAttributeTypeDef))
  11138. {
  11139. if (customAttribute.mCtorArgs.size() > 0)
  11140. {
  11141. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11142. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11143. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11144. }
  11145. if (customAttribute.mCtorArgs.size() == 2)
  11146. {
  11147. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11148. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11149. {
  11150. attributeData->mFlags = (BfAttributeFlags)constant->mInt32;
  11151. }
  11152. }
  11153. for (auto& setProp : customAttribute.mSetProperties)
  11154. {
  11155. BfPropertyDef* propDef = setProp.mPropertyRef;
  11156. if (propDef->mName == "AllowMultiple")
  11157. {
  11158. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11159. if ((constant != NULL) && (constant->mBool))
  11160. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_DisallowAllowMultiple);
  11161. else
  11162. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_DisallowAllowMultiple);
  11163. }
  11164. else if (propDef->mName == "Inherited")
  11165. {
  11166. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11167. if ((constant != NULL) && (constant->mBool))
  11168. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_NotInherited);
  11169. else
  11170. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_NotInherited);
  11171. }
  11172. else if (propDef->mName == "ValidOn")
  11173. {
  11174. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11175. if (constant != NULL)
  11176. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11177. }
  11178. else if (propDef->mName == "AlwaysIncludeUser")
  11179. {
  11180. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11181. if (constant != NULL)
  11182. attributeData->mAlwaysIncludeUser = (BfAlwaysIncludeFlags)constant->mInt32;
  11183. }
  11184. }
  11185. hasCustomAttribute = true;
  11186. }
  11187. }
  11188. }
  11189. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  11190. {
  11191. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  11192. attributeData->mFlags = mCurTypeInstance->mBaseType->mAttributeData->mFlags;
  11193. attributeData->mAlwaysIncludeUser = mCurTypeInstance->mBaseType->mAttributeData->mAlwaysIncludeUser;
  11194. }
  11195. mCurTypeInstance->mAttributeData = attributeData;
  11196. }
  11197. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  11198. {
  11199. auto constant = constHolder->GetConstant(irValue);
  11200. if (constant == NULL)
  11201. return false;
  11202. if (constant->mTypeCode != BfTypeCode_StringId)
  11203. return false;
  11204. int stringId = constant->mInt32;
  11205. BfStringPoolEntry* entry = NULL;
  11206. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  11207. {
  11208. str += entry->mString;
  11209. }
  11210. else
  11211. {
  11212. BF_DBG_FATAL("Failed to find string by id");
  11213. }
  11214. return true;
  11215. }
  11216. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  11217. {
  11218. BfVariant variant;
  11219. variant.mTypeCode = BfTypeCode_None;
  11220. BfType* primType = NULL;
  11221. if (value.mType->IsPrimitiveType())
  11222. primType = (BfPrimitiveType*)value.mType;
  11223. else if (value.mType->IsTypedPrimitive())
  11224. primType = value.mType->GetUnderlyingType();
  11225. else if (value.mType->IsInstanceOf(mCompiler->mStringTypeDef))
  11226. primType = value.mType;
  11227. if (primType)
  11228. {
  11229. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  11230. if (constant != NULL)
  11231. {
  11232. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  11233. {
  11234. variant.mUInt64 = 0;
  11235. variant.mTypeCode = BfTypeCode_Let;
  11236. return variant;
  11237. }
  11238. if (constant->mConstType == BfConstType_GlobalVar)
  11239. {
  11240. int stringIdx = GetStringPoolIdx(value.mValue, mBfIRBuilder);
  11241. if (stringIdx != -1)
  11242. {
  11243. variant.mTypeCode = BfTypeCode_StringId;
  11244. variant.mInt64 = stringIdx;
  11245. return variant;
  11246. }
  11247. }
  11248. switch (constant->mTypeCode)
  11249. {
  11250. case BfTypeCode_Boolean:
  11251. case BfTypeCode_Int8:
  11252. case BfTypeCode_UInt8:
  11253. case BfTypeCode_Int16:
  11254. case BfTypeCode_UInt16:
  11255. case BfTypeCode_Int32:
  11256. case BfTypeCode_UInt32:
  11257. case BfTypeCode_Int64:
  11258. case BfTypeCode_UInt64:
  11259. case BfTypeCode_IntPtr:
  11260. case BfTypeCode_UIntPtr:
  11261. case BfTypeCode_IntUnknown:
  11262. case BfTypeCode_UIntUnknown:
  11263. case BfTypeCode_Double:
  11264. case BfTypeCode_Char8:
  11265. case BfTypeCode_Char16:
  11266. case BfTypeCode_Char32:
  11267. case BfTypeCode_StringId:
  11268. variant.mTypeCode = constant->mTypeCode;
  11269. if (((variant.mTypeCode == BfTypeCode_Int64) || (variant.mTypeCode == BfTypeCode_UInt64)) &&
  11270. (primType->mSize > 0) && (primType->mSize < 8) &&
  11271. (mBfIRBuilder->IsIntable(primType->GetTypeCode())))
  11272. {
  11273. // We may have an 'int unknown' that we need to downsize
  11274. variant.mTypeCode = primType->GetTypeCode();
  11275. }
  11276. variant.mInt64 = constant->mInt64;
  11277. break;
  11278. case BfTypeCode_Float:
  11279. variant.mTypeCode = constant->mTypeCode;
  11280. variant.mSingle = (float)constant->mDouble;
  11281. break;
  11282. default:
  11283. if (refNode != NULL)
  11284. Fail("Invalid const expression type", refNode);
  11285. break;
  11286. }
  11287. }
  11288. }
  11289. else
  11290. {
  11291. int allocSize = value.mType->mSize + 4;
  11292. BfVariant::StructData* structData = (BfVariant::StructData*)(new uint8[allocSize]);
  11293. memset(structData, 0, allocSize);
  11294. structData->mSize = value.mType->mSize;
  11295. mBfIRBuilder->WriteConstant(value.mValue, structData->mData, value.mType);
  11296. variant.mTypeCode = BfTypeCode_Struct;
  11297. variant.mPtr = structData;
  11298. }
  11299. return variant;
  11300. }
  11301. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue, bool makeInReadOnly)
  11302. {
  11303. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  11304. {
  11305. auto refType = (BfRefType*)typedValue.mType;
  11306. auto elementType = typedValue.mType->GetUnderlyingType();
  11307. if (typedValue.IsAddr())
  11308. {
  11309. if (elementType->IsValuelessType())
  11310. {
  11311. BF_ASSERT(!typedValue.mValue);
  11312. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11313. }
  11314. else
  11315. typedValue = BfTypedValue(mBfIRBuilder->CreateAlignedLoad(typedValue.mValue, elementType->mAlign), elementType, true);
  11316. }
  11317. else
  11318. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11319. if (typedValue.mType->IsValuelessType())
  11320. {
  11321. BF_ASSERT(typedValue.mValue.IsFake());
  11322. }
  11323. if ((refType->mRefKind == BfRefType::RefKind_In) && (makeInReadOnly))
  11324. {
  11325. if (typedValue.mKind == BfTypedValueKind_Addr)
  11326. typedValue.mKind = BfTypedValueKind_ReadOnlyAddr;
  11327. }
  11328. }
  11329. return typedValue;
  11330. }
  11331. BfTypedValue BfModule::SanitizeAddr(BfTypedValue typedValue)
  11332. {
  11333. if (!typedValue)
  11334. return typedValue;
  11335. if (typedValue.mType->IsRef())
  11336. {
  11337. typedValue = LoadValue(typedValue);
  11338. auto copiedVal = BfTypedValue(CreateAlloca(typedValue.mType), typedValue.mType, true);
  11339. mBfIRBuilder->CreateStore(typedValue.mValue, copiedVal.mValue);
  11340. return copiedVal;
  11341. }
  11342. return typedValue;
  11343. }
  11344. BfTypedValue BfModule::ToRef(BfTypedValue typedValue, BfRefType* refType)
  11345. {
  11346. if (refType == NULL)
  11347. refType = CreateRefType(typedValue.mType);
  11348. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (typedValue.mType->IsObjectOrInterface()))
  11349. {
  11350. return LoadValue(typedValue);
  11351. }
  11352. if (refType->mRefKind == BfRefType::RefKind_Mut)
  11353. refType = CreateRefType(typedValue.mType);
  11354. if (!typedValue.mType->IsValuelessType())
  11355. typedValue = MakeAddressable(typedValue, false, true);
  11356. return BfTypedValue(typedValue.mValue, refType);
  11357. }
  11358. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  11359. {
  11360. if (!typedValue.IsAddr())
  11361. return typedValue;
  11362. PopulateType(typedValue.mType);
  11363. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  11364. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  11365. if (typedValue.mValue.IsConst())
  11366. {
  11367. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  11368. if (constantValue != NULL)
  11369. {
  11370. if (constantValue->mConstType == BfConstType_GlobalVar)
  11371. {
  11372. auto globalVar = (BfGlobalVar*)constantValue;
  11373. if (globalVar->mName[0] == '#')
  11374. {
  11375. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  11376. if (result)
  11377. {
  11378. // We want to avoid 'unreachable code' issues from values that
  11379. // are technically constant but change depending on compilation context
  11380. if (mCurMethodState != NULL)
  11381. {
  11382. auto checkScope = mCurMethodState->mCurScope;
  11383. while (checkScope != NULL)
  11384. {
  11385. checkScope->mSupressNextUnreachable = true;
  11386. checkScope = checkScope->mPrevScope;
  11387. }
  11388. }
  11389. return result;
  11390. }
  11391. if (!mIsComptimeModule)
  11392. return GetDefaultTypedValue(typedValue.mType);
  11393. }
  11394. }
  11395. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  11396. {
  11397. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  11398. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  11399. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  11400. auto ceTypedValue = ceDebugger->GetAddr(constantValue);
  11401. if (ceTypedValue)
  11402. {
  11403. if ((typedValue.mType->IsObjectOrInterface()) || (typedValue.mType->IsPointer()) || (typedValue.mType->IsRef()))
  11404. {
  11405. void* data = ceContext->GetMemoryPtr((addr_ce)ceTypedValue.mAddr, sizeof(addr_ce));
  11406. if (data == NULL)
  11407. {
  11408. Fail("Invalid address", refNode);
  11409. return GetDefaultTypedValue(typedValue.mType);
  11410. }
  11411. uint64 dataAddr;
  11412. if (mSystem->mPtrSize == 4)
  11413. dataAddr = *(uint32*)data;
  11414. else
  11415. dataAddr = *(uint64*)data;
  11416. return BfTypedValue(mBfIRBuilder->CreateIntToPtr(
  11417. mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataAddr), mBfIRBuilder->MapType(typedValue.mType)), typedValue.mType);
  11418. }
  11419. auto constVal = ceContext->CreateConstant(this, ceContext->mMemory.mVals + ceTypedValue.mAddr, typedValue.mType);
  11420. if (!constVal)
  11421. {
  11422. Fail("Failed to create const", refNode);
  11423. return GetDefaultTypedValue(typedValue.mType);
  11424. }
  11425. return BfTypedValue(constVal, typedValue.mType);
  11426. }
  11427. }
  11428. }
  11429. }
  11430. BfIRValue loadedVal = typedValue.mValue;
  11431. if (loadedVal)
  11432. {
  11433. if (typedValue.mType->IsVar())
  11434. {
  11435. return BfTypedValue(loadedVal, typedValue.mType, false);
  11436. }
  11437. PopulateType(typedValue.mType, BfPopulateType_Data);
  11438. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile || typedValue.IsVolatile());
  11439. }
  11440. return BfTypedValue(loadedVal, typedValue.mType, false);
  11441. }
  11442. BfTypedValue BfModule::PrepareConst(BfTypedValue& typedValue)
  11443. {
  11444. if (!typedValue.mValue.IsConst())
  11445. return typedValue;
  11446. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  11447. if (constant->mTypeCode == BfTypeCode_StringId)
  11448. return GetTypedValueFromConstant(constant, mBfIRBuilder, typedValue.mType);
  11449. return typedValue;
  11450. }
  11451. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  11452. {
  11453. if (typedValue.IsSplat())
  11454. return AggregateSplat(typedValue);
  11455. if (typedValue.IsAddr())
  11456. return LoadValue(typedValue);
  11457. return typedValue;
  11458. }
  11459. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  11460. {
  11461. if (!typedValue.IsSplat())
  11462. return typedValue;
  11463. BF_ASSERT(!mIsComptimeModule);
  11464. if (typedValue.mType->IsValuelessType())
  11465. return typedValue;
  11466. int elementIdx = 0;
  11467. auto _ExtractValue = [&](BfType* checkType)
  11468. {
  11469. if (valueArrPtr != NULL)
  11470. return valueArrPtr[elementIdx++];
  11471. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  11472. };
  11473. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11474. {
  11475. if (checkType->IsStruct())
  11476. {
  11477. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11478. auto checkTypeInstance = checkType->ToTypeInstance();
  11479. if (checkTypeInstance->mBaseType != NULL)
  11480. {
  11481. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  11482. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  11483. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  11484. }
  11485. if (checkTypeInstance->mIsUnion)
  11486. {
  11487. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11488. if (!unionInnerType->IsValuelessType())
  11489. {
  11490. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  11491. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  11492. }
  11493. if (checkTypeInstance->IsEnum())
  11494. {
  11495. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11496. BfIRValue fieldValue = checkTypeLambda(dscrType);
  11497. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  11498. }
  11499. }
  11500. else
  11501. {
  11502. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11503. {
  11504. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11505. if (fieldInstance->mDataIdx >= 0)
  11506. {
  11507. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  11508. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  11509. }
  11510. }
  11511. }
  11512. return curValue;
  11513. }
  11514. else if (checkType->IsMethodRef())
  11515. {
  11516. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11517. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11518. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11519. {
  11520. BfIRValue fieldValue;
  11521. auto checkType = methodRefType->GetCaptureType(dataIdx);
  11522. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11523. {
  11524. fieldValue = checkTypeLambda(checkType);
  11525. }
  11526. else
  11527. {
  11528. fieldValue = _ExtractValue(checkType);
  11529. }
  11530. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  11531. }
  11532. return curValue;
  11533. }
  11534. else if (!checkType->IsValuelessType())
  11535. {
  11536. return _ExtractValue(checkType);
  11537. }
  11538. return BfIRValue();
  11539. };
  11540. BfIRValue value = checkTypeLambda(typedValue.mType);
  11541. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  11542. }
  11543. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  11544. {
  11545. if (!typedValue.IsSplat())
  11546. return;
  11547. if (typedValue.mType->IsValuelessType())
  11548. return;
  11549. BF_ASSERT(!mIsComptimeModule);
  11550. /*static int sCallIdx = 0;
  11551. if (!mCompiler->mIsResolveOnly)
  11552. sCallIdx++;
  11553. int callIdx = sCallIdx;*/
  11554. int elementIdx = 0;
  11555. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  11556. {
  11557. if (checkType->IsStruct())
  11558. {
  11559. auto checkTypeInstance = checkType->ToTypeInstance();
  11560. if (checkTypeInstance->mBaseType != NULL)
  11561. {
  11562. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  11563. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  11564. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  11565. }
  11566. if (checkTypeInstance->mIsUnion)
  11567. {
  11568. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11569. if (!unionInnerType->IsValuelessType())
  11570. {
  11571. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  11572. checkTypeLambda(unionInnerType, fieldAddrVal);
  11573. }
  11574. if (checkTypeInstance->IsEnum())
  11575. {
  11576. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11577. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  11578. checkTypeLambda(dscrType, fieldAddrVal);
  11579. }
  11580. }
  11581. else
  11582. {
  11583. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11584. {
  11585. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11586. if (fieldInstance->mDataIdx >= 0)
  11587. {
  11588. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  11589. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  11590. }
  11591. }
  11592. }
  11593. }
  11594. else if (checkType->IsMethodRef())
  11595. {
  11596. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11597. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11598. {
  11599. auto dataType = methodRefType->GetCaptureType(dataIdx);
  11600. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  11601. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11602. {
  11603. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  11604. }
  11605. else
  11606. {
  11607. // static int sItrCount = 0;
  11608. // sItrCount++;
  11609. // int curItr = sItrCount;
  11610. // if (curItr == 1)
  11611. // {
  11612. // NOP;
  11613. // }
  11614. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  11615. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  11616. }
  11617. }
  11618. }
  11619. else if (!checkType->IsValuelessType())
  11620. {
  11621. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  11622. mBfIRBuilder->CreateStore(val, curAddrVal);
  11623. }
  11624. };
  11625. checkTypeLambda(typedValue.mType, addrVal);
  11626. }
  11627. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal, bool forceMutable, bool forceAddressable)
  11628. {
  11629. bool wasReadOnly = typedVal.IsReadOnly();
  11630. if ((forceAddressable) ||
  11631. ((typedVal.mType->IsValueType()) &&
  11632. (!typedVal.mType->IsValuelessType())))
  11633. {
  11634. wasReadOnly = true; // Any non-addr is implicitly read-only
  11635. //static int gCallIdx = 0;
  11636. FixValueActualization(typedVal);
  11637. if (typedVal.IsAddr())
  11638. return typedVal;
  11639. BfType* type = typedVal.mType;
  11640. PopulateType(type);
  11641. BfIRValue tempVar;
  11642. if (typedVal.mValue.IsFake())
  11643. tempVar = mBfIRBuilder->GetFakeVal();
  11644. else
  11645. {
  11646. tempVar = CreateAlloca(type);
  11647. if (typedVal.IsSplat())
  11648. AggregateSplatIntoAddr(typedVal, tempVar);
  11649. else
  11650. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  11651. }
  11652. if (forceMutable)
  11653. wasReadOnly = false;
  11654. return BfTypedValue(tempVar, type,
  11655. typedVal.IsThis() ?
  11656. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  11657. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  11658. }
  11659. return LoadValue(typedVal);
  11660. }
  11661. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  11662. {
  11663. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  11664. typedValue.mKind = BfTypedValueKind_Addr;
  11665. return typedValue;
  11666. }
  11667. BfTypedValue BfModule::CopyValue(const BfTypedValue& typedValue)
  11668. {
  11669. return MakeAddressable(LoadValue(typedValue), true);
  11670. }
  11671. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  11672. {
  11673. BF_ASSERT(!mIsComptimeModule);
  11674. BfIRValue val;
  11675. if (typedValue.mValue.IsArg())
  11676. {
  11677. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  11678. if (isAddr != NULL)
  11679. {
  11680. if (wantType != NULL)
  11681. *isAddr = wantType->IsComposite();
  11682. else
  11683. *isAddr = false;
  11684. }
  11685. else if (wantType->IsComposite())
  11686. val = mBfIRBuilder->CreateLoad(val);
  11687. }
  11688. if (!val)
  11689. {
  11690. auto checkMethodState = mCurMethodState;
  11691. while (checkMethodState != NULL)
  11692. {
  11693. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  11694. {
  11695. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  11696. if (decompAddr == typedValue.mValue)
  11697. {
  11698. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  11699. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  11700. {
  11701. // This is really backing for a POINTER to a composite inside a methodRef
  11702. val = mBfIRBuilder->CreateLoad(val);
  11703. }
  11704. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  11705. {
  11706. *isAddr = true;
  11707. return val;
  11708. }
  11709. else
  11710. {
  11711. val = mBfIRBuilder->CreateAlignedLoad(val, wantType->mAlign);
  11712. break;
  11713. }
  11714. }
  11715. }
  11716. if (val)
  11717. break;
  11718. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  11719. {
  11720. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  11721. return mBfIRBuilder->GetFakeVal();
  11722. }
  11723. checkMethodState = checkMethodState->mPrevMethodState;
  11724. }
  11725. }
  11726. if (val)
  11727. {
  11728. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  11729. {
  11730. BF_ASSERT(wantType != NULL);
  11731. if (wantType != NULL)
  11732. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  11733. }
  11734. return val;
  11735. }
  11736. BFMODULE_FATAL(this, "Splat not found");
  11737. return BfIRValue();
  11738. }
  11739. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  11740. {
  11741. int useFieldIdx = fieldIdx;
  11742. BfType* fieldType = NULL;
  11743. if (fieldInstance != NULL)
  11744. {
  11745. fieldType = fieldInstance->mResolvedType;
  11746. if (typedValue.mType->IsUnion())
  11747. {
  11748. if (fieldIdx == 1)
  11749. {
  11750. if (typedValue.IsSplat())
  11751. {
  11752. bool isAddr = false;
  11753. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  11754. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  11755. }
  11756. }
  11757. }
  11758. }
  11759. else
  11760. {
  11761. if (typedValue.mType->IsPayloadEnum())
  11762. {
  11763. auto typeInst = typedValue.mType->ToTypeInstance();
  11764. if (fieldIdx == 1)
  11765. fieldType = typeInst->GetUnionInnerType();
  11766. else if (fieldIdx == 2)
  11767. {
  11768. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  11769. }
  11770. }
  11771. else if (typedValue.mType->IsUnion())
  11772. {
  11773. if (fieldIdx == 1)
  11774. {
  11775. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  11776. if (typedValue.IsSplat())
  11777. {
  11778. bool isAddr = false;
  11779. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  11780. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  11781. }
  11782. }
  11783. }
  11784. }
  11785. BF_ASSERT(typedValue.mType->IsStruct());
  11786. if (typedValue.IsSplat())
  11787. {
  11788. if (typedValue.mType->IsPayloadEnum())
  11789. {
  11790. if (fieldIdx == 1)
  11791. {
  11792. // Payload
  11793. auto typeInst = typedValue.mType->ToTypeInstance();
  11794. auto unionInnerType = typeInst->GetUnionInnerType();
  11795. bool isAddr = false;
  11796. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  11797. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  11798. }
  11799. if (fieldIdx == 2)
  11800. {
  11801. // Discriminator
  11802. auto typeInst = typedValue.mType->ToTypeInstance();
  11803. auto unionInnerType = typeInst->GetUnionInnerType();
  11804. auto dscrType = typeInst->GetDiscriminatorType();
  11805. int argIdx = typedValue.mValue.mId;
  11806. int componentIdx = 0;
  11807. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  11808. bool isAddr;
  11809. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  11810. return BfTypedValue(irVal, dscrType, isAddr);
  11811. }
  11812. }
  11813. int componentIdx = 0;
  11814. BfTypedValue retVal;
  11815. BfFieldInstance* wantFieldInstance = fieldInstance;
  11816. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11817. {
  11818. if (checkType->IsStruct())
  11819. {
  11820. auto checkTypeInstance = checkType->ToTypeInstance();
  11821. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  11822. {
  11823. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  11824. fieldType = checkTypeInstance->GetUnionInnerType();
  11825. checkTypeLambda(fieldType);
  11826. if (checkType->IsEnum())
  11827. {
  11828. // Past discriminator...
  11829. componentIdx++;
  11830. }
  11831. return;
  11832. }
  11833. if (checkTypeInstance->mBaseType != NULL)
  11834. checkTypeLambda(checkTypeInstance->mBaseType);
  11835. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11836. {
  11837. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11838. if (fieldInstance == wantFieldInstance)
  11839. {
  11840. if (fieldInstance->mResolvedType->IsValuelessType())
  11841. {
  11842. retVal = GetDefaultTypedValue(fieldInstance->mResolvedType);
  11843. break;
  11844. }
  11845. bool isAddr = false;
  11846. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  11847. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  11848. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  11849. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  11850. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  11851. {
  11852. retVal = LoadValue(retVal);
  11853. }
  11854. break;
  11855. }
  11856. if (fieldInstance->mDataIdx >= 0)
  11857. checkTypeLambda(fieldInstance->GetResolvedType());
  11858. }
  11859. }
  11860. else if (!checkType->IsValuelessType())
  11861. {
  11862. componentIdx++;
  11863. //argIdx++;
  11864. }
  11865. };
  11866. checkTypeLambda(typedValue.mType);
  11867. BF_ASSERT(retVal);
  11868. return retVal;
  11869. }
  11870. if (typedValue.IsAddr())
  11871. {
  11872. BF_ASSERT(fieldType != NULL);
  11873. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  11874. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  11875. }
  11876. else
  11877. {
  11878. BF_ASSERT(fieldType != NULL);
  11879. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  11880. }
  11881. }
  11882. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  11883. {
  11884. if (typedValue.IsAddr())
  11885. {
  11886. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  11887. return mBfIRBuilder->CreateAlignedLoad(addrVal, typedValue.mType->mAlign);
  11888. }
  11889. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  11890. }
  11891. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  11892. {
  11893. if (isElementIndex)
  11894. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11895. else
  11896. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11897. // if (elementType->IsSizeAligned())
  11898. // {
  11899. // if (isElementIndex)
  11900. // return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11901. // else
  11902. // return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11903. // }
  11904. //
  11905. // auto ptrType = CreatePointerType(elementType);
  11906. // auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  11907. // auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  11908. // auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  11909. // BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  11910. // BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  11911. // return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  11912. }
  11913. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  11914. {
  11915. if (elementType->IsSizeAligned())
  11916. {
  11917. if (isElementIndex)
  11918. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  11919. else
  11920. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11921. }
  11922. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  11923. }
  11924. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  11925. {
  11926. if (modifyType == NULL)
  11927. modifyType = "modify";
  11928. if (typedValue.mType->IsVar())
  11929. return true;
  11930. if (typedValue.IsReadOnly())
  11931. {
  11932. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  11933. return false;
  11934. }
  11935. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  11936. {
  11937. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  11938. return false;
  11939. }
  11940. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  11941. {
  11942. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  11943. return false;
  11944. }
  11945. return true;
  11946. }
  11947. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  11948. {
  11949. // If one is an interface and the other is an impl, B is the impl
  11950. auto implOwner = methodB->GetOwner();
  11951. if (methodA->mMethodDef->mIsLocalMethod)
  11952. {
  11953. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  11954. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  11955. if (sepPosA != sepPosB)
  11956. return false;
  11957. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  11958. return false;
  11959. }
  11960. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  11961. return false;
  11962. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  11963. return false;
  11964. if (methodA->mMethodDef->mHasComptime != methodB->mMethodDef->mHasComptime)
  11965. return false;
  11966. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  11967. return false;
  11968. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  11969. {
  11970. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  11971. return false;
  11972. }
  11973. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  11974. {
  11975. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  11976. return false;
  11977. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  11978. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  11979. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  11980. return false;
  11981. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  11982. return false;
  11983. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  11984. return false;
  11985. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  11986. {
  11987. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  11988. return false;
  11989. }
  11990. }
  11991. int implicitParamCountA = methodA->GetImplicitParamCount();
  11992. int implicitParamCountB = methodB->GetImplicitParamCount();
  11993. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  11994. return false;
  11995. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  11996. return false;
  11997. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  11998. {
  11999. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  12000. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  12001. return false;
  12002. }
  12003. // Compare generic params. Generic params are part of the method signature here
  12004. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  12005. return false;
  12006. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  12007. {
  12008. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  12009. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  12010. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  12011. return false;
  12012. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  12013. return false;
  12014. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  12015. return false;
  12016. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  12017. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  12018. return false;
  12019. }
  12020. return true;
  12021. }
  12022. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  12023. {
  12024. if (!CompareMethodSignatures(methodA, methodB))
  12025. return false;
  12026. if (methodA->mReturnType != methodB->mReturnType)
  12027. return false;
  12028. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  12029. return false;
  12030. return true;
  12031. }
  12032. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  12033. {
  12034. if ((iMethodInst->GetNumGenericParams() != 0) || (methodInstance->GetNumGenericParams() != 0))
  12035. return false;
  12036. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  12037. return false;
  12038. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  12039. return false;
  12040. if (iMethodInst->mMethodDef->mIsOperator)
  12041. {
  12042. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  12043. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  12044. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  12045. return false;
  12046. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  12047. return false;
  12048. }
  12049. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  12050. return false;
  12051. auto selfType = methodInstance->GetOwner();
  12052. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  12053. {
  12054. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  12055. return false;
  12056. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  12057. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  12058. iParamType = ResolveSelfType(iParamType, selfType);
  12059. methodParamType = ResolveSelfType(methodParamType, selfType);
  12060. if (!iParamType->IsGenericParam())
  12061. {
  12062. if (methodParamType != iParamType)
  12063. return false;
  12064. }
  12065. else
  12066. {
  12067. if (!methodParamType->IsGenericParam())
  12068. return false;
  12069. auto genericParamType = (BfGenericParamType*)methodParamType;
  12070. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  12071. return false;
  12072. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12073. bool hadInterface = false;
  12074. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  12075. if (interfaceConstraint == iParamType)
  12076. hadInterface = true;
  12077. if (!hadInterface)
  12078. return false;
  12079. }
  12080. }
  12081. return true;
  12082. }
  12083. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  12084. {
  12085. BfMethodInstance* methodInstance = methodRef;
  12086. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  12087. {
  12088. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  12089. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  12090. {
  12091. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  12092. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  12093. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12094. BfMethodRef methodRef = methodInstance;
  12095. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  12096. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  12097. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  12098. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  12099. (mIsReified))
  12100. {
  12101. specializedMethodRefInfo->mHasReifiedRef = true;
  12102. }
  12103. }
  12104. }
  12105. }
  12106. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  12107. {
  12108. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  12109. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12110. if (mBfIRBuilder == NULL)
  12111. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12112. if (methodInstance->GetOwner()->IsFunction())
  12113. {
  12114. // No actual ref needed- not an actual generated function
  12115. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12116. }
  12117. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  12118. if (!isGenFunction)
  12119. AddMethodReference(methodInstance, flags);
  12120. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  12121. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  12122. if (IsSkippingExtraResolveChecks())
  12123. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12124. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  12125. {
  12126. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12127. }
  12128. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12129. if ((methodInstance->mIsIntrinsic) || (methodInstance->mMethodDef->mIsExtern))
  12130. isInlined = false;
  12131. BfMethodRef methodRef = methodInstance;
  12132. if (isInlined)
  12133. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  12134. else
  12135. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  12136. if (!isGenFunction)
  12137. {
  12138. BfIRValue* irFuncPtr = NULL;
  12139. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  12140. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  12141. }
  12142. if (mAwaitingInitFinish)
  12143. FinishInit();
  12144. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  12145. if (!isGenFunction)
  12146. {
  12147. BF_ASSERT(func || methodInstance->mMethodInstanceGroup->mOwner->IsInterface());
  12148. mFuncReferences[methodRef] = func;
  12149. }
  12150. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  12151. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12152. {
  12153. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  12154. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  12155. // type instance
  12156. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  12157. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  12158. for (auto ownedTypeInst : mOwnedTypeInstances)
  12159. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  12160. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  12161. {
  12162. mIncompleteMethodCount++;
  12163. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12164. inlineMethodRequest->mType = methodInstance->GetOwner();
  12165. inlineMethodRequest->mFromModule = this;
  12166. inlineMethodRequest->mFunc = func;
  12167. inlineMethodRequest->mFromModuleRevision = mRevision;
  12168. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  12169. inlineMethodRequest->mMethodInstance = methodInstance;
  12170. BF_ASSERT(mIsModuleMutable);
  12171. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12172. }
  12173. }
  12174. return BfModuleMethodInstance(methodInstance, func);
  12175. }
  12176. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  12177. {
  12178. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  12179. if (mBfIRBuilder == NULL)
  12180. {
  12181. // To allow for custom attribute data
  12182. PrepareForIRWriting(typeInst);
  12183. }
  12184. BfModule* declareModule = this;
  12185. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  12186. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  12187. declareModule = declareModule->mParentModule;
  12188. // Check for attributes
  12189. if (typeInst == mContext->mBfObjectType)
  12190. {
  12191. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  12192. if (methodDecl != NULL)
  12193. {
  12194. auto attributesDirective = methodDecl->mAttributes;
  12195. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  12196. {
  12197. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  12198. sourceClassifier->VisitChild(attributesDirective);
  12199. }
  12200. }
  12201. }
  12202. else
  12203. {
  12204. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  12205. GetMethodCustomAttributes(methodInstance);
  12206. }
  12207. BF_ASSERT(mModuleOptions == NULL);
  12208. if (methodInstance->GetCustomAttributes() != NULL)
  12209. {
  12210. auto project = typeInst->mTypeDef->mProject;
  12211. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  12212. BfModuleOptions wantOptions = moduleOptions;
  12213. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  12214. if (typeOptions != NULL)
  12215. {
  12216. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  12217. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  12218. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  12219. }
  12220. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  12221. {
  12222. StringT<128> attrName;
  12223. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  12224. {
  12225. attrName.Clear();
  12226. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  12227. Array<int>* arrPtr;
  12228. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  12229. {
  12230. for (auto optionsIdx : *arrPtr)
  12231. {
  12232. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  12233. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  12234. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  12235. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  12236. }
  12237. }
  12238. }
  12239. }
  12240. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  12241. {
  12242. auto lastCheckModule = this;
  12243. auto checkModule = this->mNextAltModule;
  12244. while (checkModule != NULL)
  12245. {
  12246. if (*checkModule->mModuleOptions == wantOptions)
  12247. {
  12248. declareModule = checkModule;
  12249. break;
  12250. }
  12251. lastCheckModule = checkModule;
  12252. checkModule = checkModule->mNextAltModule;
  12253. }
  12254. // Not found?
  12255. if (declareModule == this)
  12256. {
  12257. String specModuleName = mModuleName + "@@";
  12258. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  12259. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  12260. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  12261. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  12262. declareModule = new BfModule(mContext, specModuleName);
  12263. declareModule->mProject = project;
  12264. declareModule->mModuleOptions = new BfModuleOptions();
  12265. *declareModule->mModuleOptions = wantOptions;
  12266. declareModule->mParentModule = lastCheckModule;
  12267. declareModule->Init();
  12268. lastCheckModule->mNextAltModule = declareModule;
  12269. }
  12270. }
  12271. }
  12272. declareModule->PrepareForIRWriting(typeInst);
  12273. return declareModule;
  12274. }
  12275. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType, BfModule* referencingModule)
  12276. {
  12277. if (methodDef->mMethodType == BfMethodType_Init)
  12278. return BfModuleMethodInstance();
  12279. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  12280. {
  12281. // Don't bother inlining for resolve-only
  12282. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12283. }
  12284. if (methodDef->mIsExtern)
  12285. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12286. bool processNow = false;
  12287. bool keepInCurrentModule = false;
  12288. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  12289. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  12290. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  12291. {
  12292. return BfModuleMethodInstance();
  12293. }
  12294. if (methodDef->mIsLocalMethod)
  12295. {
  12296. auto rootMethodState = mCurMethodState->GetRootMethodState();
  12297. BfLocalMethod* localMethod;
  12298. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  12299. {
  12300. // Handle the def in the correct method state
  12301. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  12302. }
  12303. BFMODULE_FATAL(this, "Cannot find local method");
  12304. return BfModuleMethodInstance();
  12305. }
  12306. #ifdef _DEBUG
  12307. for (auto arg : methodGenericArguments)
  12308. BF_ASSERT(!arg->IsVar());
  12309. #endif
  12310. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  12311. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  12312. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  12313. // a FinishInit
  12314. if ((typeInst->IsIncomplete()) &&
  12315. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  12316. {
  12317. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  12318. // for resolve-only because we don't differentiate between reified/unreified there
  12319. if ((methodDef->mIsStatic) /*&& (mIsComptimeModule)*/)
  12320. {
  12321. if (!typeInst->DefineStateAllowsStaticMethods())
  12322. PopulateType(typeInst, BfPopulateType_AllowStaticMethods);
  12323. }
  12324. else
  12325. PopulateType(typeInst, BfPopulateType_Full);
  12326. if (typeInst->mDefineState < BfTypeDefineState_Defined)
  12327. {
  12328. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12329. {
  12330. BfLogSysM("GetMethodInstance (DefineState < BfTypeDefineState_Defined)) bailing due to IsCePaused\n");
  12331. return BfModuleMethodInstance();
  12332. }
  12333. }
  12334. }
  12335. bool tryModuleMethodLookup = false;
  12336. BfModuleMethodInstance moduleMethodInst;
  12337. BfModule* instModule = typeInst->mModule;
  12338. if (keepInCurrentModule)
  12339. {
  12340. // Stay here
  12341. instModule = this;
  12342. }
  12343. if (this == mContext->mUnreifiedModule)
  12344. {
  12345. // Stay in this 'resolve only' module here
  12346. }
  12347. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  12348. {
  12349. BF_ASSERT(this == mContext->mUnreifiedModule);
  12350. }
  12351. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  12352. {
  12353. BF_ASSERT(instModule == mParentModule);
  12354. }
  12355. else if (instModule != this)
  12356. {
  12357. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12358. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  12359. if ((!mIsComptimeModule) && (!mIsReified) && (instModule->mIsReified))
  12360. {
  12361. BF_ASSERT(!mCompiler->mIsResolveOnly);
  12362. // A resolve-only module is specializing a method from a type in a reified module,
  12363. // we need to take care that this doesn't cause anything new to become reified
  12364. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  12365. if (!moduleMethodInstance)
  12366. return moduleMethodInstance;
  12367. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  12368. return moduleMethodInstance;
  12369. }
  12370. else
  12371. {
  12372. if ((!mIsComptimeModule) && (mIsReified) && (!instModule->mIsReified))
  12373. {
  12374. if (!typeInst->IsUnspecializedType())
  12375. {
  12376. if (!instModule->mReifyQueued)
  12377. {
  12378. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  12379. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  12380. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  12381. mContext->mReifyModuleWorkList.Add(instModule);
  12382. instModule->mReifyQueued = true;
  12383. }
  12384. 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);
  12385. // This ensures that the method will actually be created when it gets reified
  12386. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  12387. specializationRequest->mFromModule = typeInst->mModule;
  12388. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  12389. specializationRequest->Init(typeInst, foreignType, methodDef);
  12390. //specializationRequest->mMethodDef = methodDef;
  12391. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  12392. specializationRequest->mType = typeInst;
  12393. specializationRequest->mFlags = flags;
  12394. }
  12395. }
  12396. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12397. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoReference);
  12398. if (mIsComptimeModule)
  12399. {
  12400. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12401. if (!mCompiler->mIsResolveOnly)
  12402. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification | BfGetMethodInstanceFlag_Unreified | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12403. }
  12404. // Not extern
  12405. // Create the instance in the proper module and then create a reference in this one
  12406. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType, this);
  12407. if (!moduleMethodInst)
  12408. return moduleMethodInst;
  12409. tryModuleMethodLookup = true;
  12410. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  12411. {
  12412. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  12413. }
  12414. }
  12415. }
  12416. if (tryModuleMethodLookup)
  12417. {
  12418. SetMethodDependency(moduleMethodInst.mMethodInstance);
  12419. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  12420. }
  12421. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  12422. {
  12423. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  12424. if (moduleMethodInstance)
  12425. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  12426. return moduleMethodInst;
  12427. }
  12428. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  12429. bool hadConcreteInterfaceGenericArgument = false;
  12430. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  12431. isReified = false;
  12432. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  12433. {
  12434. isReified = false;
  12435. }
  12436. BfTypeVector sanitizedMethodGenericArguments;
  12437. SizedArray<BfProject*, 4> projectList;
  12438. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  12439. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  12440. isUnspecializedPass = false;
  12441. // 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
  12442. bool isExternalExtensionMethod = false;
  12443. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  12444. {
  12445. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) &&
  12446. (methodDef->mDeclaringType != NULL) &&
  12447. (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  12448. {
  12449. auto specProject = methodDef->mDeclaringType->mProject;
  12450. isExternalExtensionMethod = true;
  12451. if (typeInst->IsGenericTypeInstance())
  12452. {
  12453. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12454. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12455. genericTypeInst->GenerateProjectsReferenced();
  12456. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  12457. {
  12458. // This is a generic type where a generic param is already confined to the project in question
  12459. isExternalExtensionMethod = false;
  12460. }
  12461. }
  12462. if (isExternalExtensionMethod)
  12463. {
  12464. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  12465. projectList.push_back(methodDef->mDeclaringType->mProject);
  12466. }
  12467. }
  12468. }
  12469. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  12470. {
  12471. int typeProjectsCounts = 0;
  12472. if (typeInst->IsGenericTypeInstance())
  12473. {
  12474. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12475. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12476. genericTypeInst->GenerateProjectsReferenced();
  12477. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  12478. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  12479. }
  12480. else
  12481. {
  12482. typeProjectsCounts = 1;
  12483. projectList.Insert(0, typeInst->mTypeDef->mProject);
  12484. }
  12485. isUnspecializedPass = true;
  12486. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  12487. {
  12488. auto genericArgType = methodGenericArguments[genericArgIdx];
  12489. //BF_ASSERT(!genericArgType->IsRef());
  12490. if (genericArgType->IsConcreteInterfaceType())
  12491. {
  12492. hadConcreteInterfaceGenericArgument = true;
  12493. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  12494. genericArgType = concreteInterfaceType->mInterface;
  12495. }
  12496. if (genericArgType->IsGenericParam())
  12497. {
  12498. auto genericParam = (BfGenericParamType*) genericArgType;
  12499. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  12500. isUnspecializedPass = false;
  12501. }
  12502. else
  12503. {
  12504. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  12505. isUnspecializedPass = false;
  12506. }
  12507. sanitizedMethodGenericArguments.push_back(genericArgType);
  12508. }
  12509. if ((int)projectList.size() > typeProjectsCounts)
  12510. {
  12511. // Just leave the new items
  12512. projectList.RemoveRange(0, typeProjectsCounts);
  12513. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  12514. {
  12515. return lhs->mName < rhs->mName;
  12516. });
  12517. }
  12518. else
  12519. {
  12520. projectList.Clear();
  12521. }
  12522. }
  12523. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  12524. BfMethodInstanceGroup* methodInstGroup = NULL;
  12525. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12526. {
  12527. BF_ASSERT(!typeInst->IsInterface());
  12528. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  12529. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  12530. {
  12531. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  12532. // if (checkGroup.mDefault == NULL)
  12533. // {
  12534. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  12535. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  12536. // methodInstGroup = &checkGroup;
  12537. // break;
  12538. // }
  12539. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  12540. {
  12541. methodInstGroup = &checkGroup;
  12542. break;
  12543. }
  12544. }
  12545. if (methodInstGroup == NULL)
  12546. {
  12547. if (lookupMethodGenericArguments.size() != 0)
  12548. {
  12549. BF_ASSERT((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0);
  12550. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12551. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12552. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12553. }
  12554. else
  12555. {
  12556. // Allocate a new entry
  12557. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  12558. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  12559. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  12560. methodInstGroup->mOwner = typeInst;
  12561. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12562. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12563. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  12564. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12565. else
  12566. {
  12567. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  12568. if (!mIsScratchModule)
  12569. mOnDemandMethodCount++;
  12570. }
  12571. }
  12572. }
  12573. }
  12574. else
  12575. {
  12576. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  12577. }
  12578. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12579. {
  12580. if (typeInst->mDefineState > BfTypeDefineState_DefinedAndMethodsSlotted)
  12581. {
  12582. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  12583. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12584. }
  12585. }
  12586. BfIRFunction prevIRFunc;
  12587. bool doingRedeclare = false;
  12588. BfMethodInstance* methodInstance = NULL;
  12589. auto _SetReified = [&]()
  12590. {
  12591. if (!mCompiler->mIsResolveOnly)
  12592. BF_ASSERT(mCompiler->mCompileState <= BfCompiler::CompileState_Normal);
  12593. methodInstance->mIsReified = true;
  12594. };
  12595. if (lookupMethodGenericArguments.size() == 0)
  12596. {
  12597. methodInstance = methodInstGroup->mDefault;
  12598. if ((methodInstance != NULL) && ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0))
  12599. return methodInstance;
  12600. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  12601. {
  12602. MarkDerivedDirty(typeInst);
  12603. if (!HasCompiledOutput())
  12604. {
  12605. BfLogSysM("Marking non-compiled-output module method instance as reified: %p\n", methodInstance);
  12606. _SetReified();
  12607. CheckHotMethod(methodInstance, "");
  12608. }
  12609. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  12610. {
  12611. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  12612. // the specializations to handle that for us
  12613. return BfModuleMethodInstance(methodInstance);
  12614. }
  12615. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  12616. {
  12617. if (methodDef->mIsAbstract)
  12618. {
  12619. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12620. _SetReified();
  12621. }
  12622. else
  12623. {
  12624. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12625. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  12626. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  12627. doingRedeclare = true;
  12628. mOnDemandMethodCount++;
  12629. VerifyOnDemandMethods();
  12630. }
  12631. }
  12632. else
  12633. {
  12634. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  12635. // We haven't processed it yet
  12636. _SetReified();
  12637. CheckHotMethod(methodInstance, "");
  12638. if (methodInstance->mDeclModule == this)
  12639. {
  12640. if (methodInstance->mMethodProcessRequest != NULL)
  12641. {
  12642. // Disconnect method process request
  12643. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  12644. }
  12645. }
  12646. else
  12647. {
  12648. if (methodInstance->mMethodProcessRequest != NULL)
  12649. {
  12650. // Disconnect method process request
  12651. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  12652. methodInstance->mMethodProcessRequest = NULL;
  12653. }
  12654. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  12655. {
  12656. // Add new request in proper module
  12657. methodInstance->mDeclModule = this;
  12658. }
  12659. else
  12660. {
  12661. if (methodInstance->mDeclModule == NULL)
  12662. {
  12663. //
  12664. }
  12665. else if (methodInstance->mDeclModule != this)
  12666. {
  12667. // Is from specialized module?
  12668. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  12669. }
  12670. }
  12671. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12672. {
  12673. methodInstance->mIRFunction = BfIRFunction();
  12674. if (!mIsModuleMutable)
  12675. StartExtension();
  12676. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  12677. {
  12678. StringT<512> mangledName;
  12679. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  12680. bool isIntrinsic = false;
  12681. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  12682. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  12683. }
  12684. }
  12685. AddMethodToWorkList(methodInstance);
  12686. }
  12687. }
  12688. }
  12689. }
  12690. else
  12691. {
  12692. if (methodInstGroup->mDefault == NULL)
  12693. {
  12694. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12695. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12696. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12697. }
  12698. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  12699. if (methodInstGroup->mMethodSpecializationMap == NULL)
  12700. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  12701. BfMethodInstance** methodInstancePtr = NULL;
  12702. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  12703. {
  12704. methodInstance = *methodInstancePtr;
  12705. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  12706. return methodInstance;
  12707. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  12708. {
  12709. BfLogSysM("Setting mRequestedByAutocomplete=false for method instance %p\n", methodInstance);
  12710. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  12711. if (methodInstance->mMethodProcessRequest == NULL)
  12712. AddMethodToWorkList(methodInstance);
  12713. methodInstance->mRequestedByAutocomplete = false;
  12714. }
  12715. if ((isReified) && (!methodInstance->mIsReified))
  12716. {
  12717. MarkDerivedDirty(typeInst);
  12718. if (methodInstance->mHasBeenProcessed)
  12719. {
  12720. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  12721. delete methodInstance;
  12722. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12723. methodInstance = NULL;
  12724. }
  12725. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12726. {
  12727. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  12728. delete methodInstance;
  12729. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12730. methodInstance = NULL;
  12731. }
  12732. else
  12733. {
  12734. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  12735. // We haven't processed it yet
  12736. _SetReified();
  12737. CheckHotMethod(methodInstance, "");
  12738. if (methodInstance->mMethodProcessRequest == NULL)
  12739. AddMethodToWorkList(methodInstance);
  12740. }
  12741. }
  12742. }
  12743. }
  12744. if ((methodInstance != NULL) && (!doingRedeclare))
  12745. {
  12746. SetMethodDependency(methodInstance);
  12747. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  12748. {
  12749. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  12750. BF_ASSERT(!methodInstance->mIsReified);*/
  12751. if ((!mCompiler->mIsResolveOnly) && (isReified))
  12752. {
  12753. auto refModule = referencingModule;
  12754. if (refModule == NULL)
  12755. refModule = this;
  12756. 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);
  12757. }
  12758. if (methodInstance->mIsReified != isReified)
  12759. {
  12760. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  12761. }
  12762. if ((!isReified) &&
  12763. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  12764. {
  12765. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  12766. methodInstance->mIRFunction = BfIRFunction();
  12767. }
  12768. methodInstance->mIsReified = isReified;
  12769. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  12770. {
  12771. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  12772. }
  12773. if (!methodInstance->mMethodDef->mIsAbstract)
  12774. {
  12775. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  12776. {
  12777. // Wait until unreified
  12778. }
  12779. else
  12780. AddMethodToWorkList(methodInstance);
  12781. }
  12782. else
  12783. {
  12784. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  12785. auto owningModule = methodInstance->GetOwner()->mModule;
  12786. if (!owningModule->mIsScratchModule)
  12787. {
  12788. owningModule->mOnDemandMethodCount--;
  12789. owningModule->VerifyOnDemandMethods();
  12790. }
  12791. }
  12792. }
  12793. if (mExtensionCount > 0)
  12794. {
  12795. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  12796. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  12797. {
  12798. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  12799. if (mAwaitingInitFinish)
  12800. FinishInit();
  12801. // We need to refer to a function that was defined in a prior module
  12802. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12803. if (methodInstance->mIsIntrinsic)
  12804. isInlined = false;
  12805. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  12806. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  12807. methodInstance->mDeclModule = this;
  12808. // Add this inlined def to ourselves
  12809. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12810. {
  12811. mIncompleteMethodCount++;
  12812. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12813. inlineMethodRequest->mType = typeInst;
  12814. inlineMethodRequest->mFromModule = this;
  12815. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  12816. inlineMethodRequest->mFromModuleRevision = mRevision;
  12817. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  12818. inlineMethodRequest->mMethodInstance = methodInstance;
  12819. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12820. BF_ASSERT(mIsModuleMutable);
  12821. }
  12822. }
  12823. }
  12824. if (IsSkippingExtraResolveChecks())
  12825. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12826. else
  12827. {
  12828. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12829. return methodInstance;
  12830. if (methodInstance->mDeclModule != this)
  12831. return ReferenceExternalMethodInstance(methodInstance, flags);
  12832. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  12833. {
  12834. auto importKind = methodInstance->GetImportCallKind();
  12835. if (importKind != BfImportCallKind_None)
  12836. {
  12837. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  12838. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  12839. auto func = CreateDllImportGlobalVar(methodInstance, true);
  12840. BF_ASSERT(func);
  12841. mFuncReferences[methodInstance] = func;
  12842. }
  12843. }
  12844. return BfModuleMethodInstance(methodInstance);
  12845. }
  12846. }
  12847. if (!doingRedeclare)
  12848. {
  12849. BfModule* specModule = NULL;
  12850. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  12851. {
  12852. specModule = GetSpecializedMethodModule(projectList);
  12853. }
  12854. if ((specModule != NULL) && (specModule != this))
  12855. {
  12856. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  12857. if (mAwaitingInitFinish)
  12858. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  12859. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12860. return specMethodInstance.mMethodInstance;
  12861. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  12862. }
  12863. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  12864. {
  12865. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  12866. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  12867. }
  12868. }
  12869. if (methodInstance == NULL)
  12870. {
  12871. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12872. {
  12873. BfLogSysM("GetMethodInstance (methodInstance == NULL) bailing due to IsCePaused\n");
  12874. return BfModuleMethodInstance();
  12875. }
  12876. if (lookupMethodGenericArguments.size() == 0)
  12877. {
  12878. BF_ASSERT(methodInstGroup->mDefault == NULL);
  12879. methodInstance = new BfMethodInstance();
  12880. methodInstGroup->mDefault = methodInstance;
  12881. BF_ASSERT(typeInst->mDefineState > BfTypeDefineState_Declared);
  12882. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  12883. }
  12884. else
  12885. {
  12886. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  12887. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12888. depthExceeded = true;
  12889. if (depthExceeded)
  12890. {
  12891. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  12892. return BfModuleMethodInstance();
  12893. }
  12894. BfMethodInstance** methodInstancePtr = NULL;
  12895. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  12896. BF_ASSERT(added);
  12897. methodInstance = new BfMethodInstance();
  12898. *methodInstancePtr = methodInstance;
  12899. if (mCompiler->IsAutocomplete())
  12900. methodInstance->mRequestedByAutocomplete = true;
  12901. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  12902. }
  12903. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  12904. methodInstance->mIRFunction = prevIRFunc; // Take it over
  12905. }
  12906. methodInstance->mMethodDef = methodDef;
  12907. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  12908. methodInstance->mMethodInstanceGroup = methodInstGroup;
  12909. methodInstance->mIsReified = isReified;
  12910. SetupMethodIdHash(methodInstance);
  12911. if (hadConcreteInterfaceGenericArgument)
  12912. methodInstance->mIgnoreBody = true;
  12913. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12914. {
  12915. methodInstance->mIsForeignMethodDef = true;
  12916. BF_ASSERT(foreignType != NULL);
  12917. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  12918. }
  12919. if ((typeInst->IsInstanceOf(mCompiler->mValueTypeTypeDef)) && (methodDef->mName == BF_METHODNAME_EQUALS))
  12920. {
  12921. if (!lookupMethodGenericArguments.empty())
  12922. {
  12923. auto compareType = lookupMethodGenericArguments[0];
  12924. PopulateType(compareType, BfPopulateType_Data);
  12925. if (compareType->IsSplattable())
  12926. methodInstance->mAlwaysInline = true;
  12927. }
  12928. }
  12929. if (methodDef->mMethodType == BfMethodType_Init)
  12930. {
  12931. methodInstance->mMangleWithIdx = true;
  12932. }
  12933. BF_ASSERT(typeInst == methodInstance->GetOwner());
  12934. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12935. if (isUnspecializedPass)
  12936. {
  12937. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  12938. {
  12939. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  12940. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  12941. }
  12942. }
  12943. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  12944. {
  12945. if (!sanitizedMethodGenericArguments.IsEmpty())
  12946. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  12947. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  12948. {
  12949. Fail("Internal error");
  12950. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  12951. return NULL;
  12952. }
  12953. for (auto genericArg : sanitizedMethodGenericArguments)
  12954. {
  12955. if (genericArg->IsPrimitiveType())
  12956. genericArg = GetWrappedStructType(genericArg);
  12957. if (genericArg != NULL)
  12958. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  12959. }
  12960. }
  12961. // Generic constraints
  12962. if (!methodDef->mGenericParams.IsEmpty())
  12963. {
  12964. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  12965. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  12966. {
  12967. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  12968. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12969. }
  12970. }
  12971. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  12972. {
  12973. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  12974. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12975. }
  12976. bool addToWorkList = !processNow;
  12977. if (mCompiler->GetAutoComplete() != NULL)
  12978. {
  12979. if (typeInst->IsSpecializedByAutoCompleteMethod())
  12980. addToWorkList = false;
  12981. if (methodInstance->mRequestedByAutocomplete)
  12982. addToWorkList = false;
  12983. }
  12984. BfModule* declareModule;
  12985. //
  12986. {
  12987. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  12988. declareModule = GetOrCreateMethodModule(methodInstance);
  12989. }
  12990. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  12991. declareModule = methodInstance->mDeclModule;
  12992. BF_ASSERT(declareModule != NULL);
  12993. methodInstance->mDeclModule = declareModule;
  12994. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  12995. {
  12996. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  12997. // of a reified module -
  12998. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  12999. // BUT if we don't reify it then we have to remove the body after processing.
  13000. // 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
  13001. // the proper reified module.
  13002. declareModule = mContext->mUnreifiedModule;
  13003. }
  13004. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  13005. {
  13006. if (!methodInstance->mIsReified)
  13007. {
  13008. declareModule = mContext->mUnreifiedModule;
  13009. }
  13010. else
  13011. {
  13012. declareModule->PrepareForIRWriting(methodInstance->GetOwner());
  13013. }
  13014. }
  13015. SetMethodDependency(methodInstance);
  13016. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  13017. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  13018. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  13019. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  13020. {
  13021. // For mixins we only process the unspecialized version
  13022. addToWorkList = false;
  13023. }
  13024. if (((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0) && (methodInstGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  13025. {
  13026. addToWorkList = false;
  13027. }
  13028. // if ((flags & BfGetMethodInstanceFlag_NoReference) != 0)
  13029. // addToWorkList = false;
  13030. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  13031. if (processNow)
  13032. {
  13033. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  13034. ProcessMethod(methodInstance);
  13035. }
  13036. if (IsSkippingExtraResolveChecks())
  13037. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  13038. if (methodInstance->mDeclModule != this)
  13039. return ReferenceExternalMethodInstance(methodInstance, flags);
  13040. return BfModuleMethodInstance(methodInstance);
  13041. }
  13042. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  13043. {
  13044. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  13045. if (methodInstance->mIsForeignMethodDef)
  13046. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  13047. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  13048. }
  13049. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  13050. {
  13051. if (!methodInstance->mMethodDef->mIsLocalMethod)
  13052. return NULL;
  13053. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  13054. if (outerLocal == NULL)
  13055. return NULL;
  13056. BfTypeVector genericArgs;
  13057. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  13058. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  13059. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  13060. }
  13061. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  13062. {
  13063. HashContext hashCtx;
  13064. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  13065. {
  13066. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  13067. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  13068. if (methodInstance->GetNumGenericArguments() != 0)
  13069. {
  13070. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  13071. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13072. hashCtx.Mixin(methodGenericArg->mTypeId);
  13073. }
  13074. };
  13075. _MixinMethodInstance(methodInstance);
  13076. if (methodInstance->mMethodDef->mIsLocalMethod)
  13077. {
  13078. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  13079. if (outmostMethodInstance != NULL)
  13080. {
  13081. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  13082. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  13083. }
  13084. }
  13085. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  13086. }
  13087. bool BfModule::CheckUseMethodInstance(BfMethodInstance* methodInstance, BfAstNode* refNode)
  13088. {
  13089. if (methodInstance->mHasBeenDeclared)
  13090. return true;
  13091. Fail(StrFormat("Circular reference in method instance '%s'", MethodToString(methodInstance).c_str()), refNode);
  13092. return false;
  13093. }
  13094. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  13095. {
  13096. BfIRValue globalValue;
  13097. BfIRValue* globalValuePtr = NULL;
  13098. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  13099. {
  13100. globalValue = *globalValuePtr;
  13101. }
  13102. if (!globalValue)
  13103. {
  13104. // This is necessary to reify the interface type
  13105. PopulateType(ifaceType);
  13106. StringT<512> slotVarName;
  13107. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  13108. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  13109. BfIRValue value;
  13110. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  13111. {
  13112. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  13113. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  13114. int virtSlotIdx = ifaceType->mSlotNum + 1;
  13115. value = GetConstValue32(virtSlotIdx);*/
  13116. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  13117. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  13118. }
  13119. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  13120. mInterfaceSlotRefs[ifaceType] = globalValue;
  13121. // Make sure we reify
  13122. PopulateType(ifaceType, BfPopulateType_Declaration);
  13123. AddDependency(ifaceType, mCurTypeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  13124. }
  13125. return mBfIRBuilder->CreateAlignedLoad(globalValue/*, "slotOfs"*/, 4);
  13126. }
  13127. void BfModule::HadSlotCountDependency()
  13128. {
  13129. if (mCompiler->mIsResolveOnly)
  13130. return;
  13131. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  13132. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  13133. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  13134. }
  13135. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  13136. {
  13137. if (str == "#IsComptime")
  13138. {
  13139. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsComptimeModule ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13140. }
  13141. if (str == "#IsBuilding")
  13142. {
  13143. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (!mCompiler->mIsResolveOnly) ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13144. }
  13145. if (str == "#IsReified")
  13146. {
  13147. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsReified ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13148. }
  13149. if (str == "#CompileRev")
  13150. {
  13151. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mRevision), GetPrimitiveType(BfTypeCode_Int32));
  13152. }
  13153. if (str == "#NextId")
  13154. {
  13155. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)++mCompiler->mUniqueId), GetPrimitiveType(BfTypeCode_Int32));
  13156. }
  13157. if (str == "#ModuleName")
  13158. {
  13159. return BfTypedValue(GetStringObjectValue(mModuleName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13160. }
  13161. if (str == "#ProjectName")
  13162. {
  13163. if (mProject != NULL)
  13164. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13165. }
  13166. if (str == "#AllocStackCount")
  13167. {
  13168. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mOptions.mAllocStackCount), GetPrimitiveType(BfTypeCode_Int32));
  13169. }
  13170. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  13171. {
  13172. if (str == "#CallerLineNum")
  13173. {
  13174. return BfTypedValue(GetConstValue(mCurMethodState->mMixinState->mInjectFilePosition.mCurLine + 1), GetPrimitiveType(BfTypeCode_Int32));
  13175. }
  13176. else if (str == "#CallerFilePath")
  13177. {
  13178. String filePath = "";
  13179. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13180. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13181. return BfTypedValue(GetStringObjectValue(filePath), ResolveTypeDef(mCompiler->mStringTypeDef));
  13182. }
  13183. else if (str == "#CallerFileName")
  13184. {
  13185. String filePath = "";
  13186. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13187. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13188. return BfTypedValue(GetStringObjectValue(GetFileName(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13189. }
  13190. else if (str == "#CallerFileDir")
  13191. {
  13192. String filePath = "";
  13193. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13194. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13195. return BfTypedValue(GetStringObjectValue(GetFileDir(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13196. }
  13197. else if (str == "#CallerTypeName")
  13198. {
  13199. String typeName = "";
  13200. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13201. typeName = TypeToString(mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner());
  13202. return BfTypedValue(GetStringObjectValue(typeName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13203. }
  13204. else if (str == "#CallerType")
  13205. {
  13206. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  13207. BfType* type = NULL;
  13208. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13209. type = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  13210. if (type != NULL)
  13211. {
  13212. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  13213. return BfTypedValue(CreateTypeDataRef(type), typeType);
  13214. }
  13215. }
  13216. else if (str == "#CallerMemberName")
  13217. {
  13218. String memberName = "";
  13219. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13220. memberName = MethodToString(mCurMethodState->mMixinState->mMixinMethodInstance);
  13221. return BfTypedValue(GetStringObjectValue(memberName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13222. }
  13223. else if (str == "#CallerProject")
  13224. {
  13225. BfProject* project = NULL;
  13226. project = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mProject;
  13227. if (project != NULL)
  13228. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13229. }
  13230. }
  13231. if (str == "#TimeLocal")
  13232. {
  13233. time_t rawtime;
  13234. time(&rawtime);
  13235. tm* timeinfo = localtime(&rawtime);
  13236. char result[32];
  13237. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  13238. 1900 + timeinfo->tm_year,
  13239. timeinfo->tm_mon + 1,
  13240. timeinfo->tm_mday,
  13241. timeinfo->tm_hour,
  13242. timeinfo->tm_min,
  13243. timeinfo->tm_sec);
  13244. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  13245. }
  13246. return BfTypedValue();
  13247. }
  13248. BfTypedValue BfModule::GetCompilerFieldValue(BfTypedValue typedValue)
  13249. {
  13250. if (!typedValue.IsAddr())
  13251. return BfTypedValue();
  13252. if (typedValue.mValue.IsConst())
  13253. {
  13254. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  13255. if (constantValue != NULL)
  13256. {
  13257. if (constantValue->mConstType == BfConstType_GlobalVar)
  13258. {
  13259. auto globalVar = (BfGlobalVar*)constantValue;
  13260. if (globalVar->mName[0] == '#')
  13261. {
  13262. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  13263. return result;
  13264. }
  13265. }
  13266. }
  13267. }
  13268. return BfTypedValue();
  13269. }
  13270. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  13271. {
  13272. BfIRValue globalValue;
  13273. auto fieldDef = fieldInstance->GetFieldDef();
  13274. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  13275. {
  13276. if (fieldInstance->mConstIdx != -1)
  13277. {
  13278. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  13279. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  13280. }
  13281. else
  13282. {
  13283. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  13284. }
  13285. }
  13286. if ((mIsScratchModule) && (mCompiler->mIsResolveOnly) && (!fieldInstance->mOwner->IsInstanceOf(mCompiler->mCompilerTypeDef)))
  13287. {
  13288. // Just fake it for the extern and unspecialized modules
  13289. // We can't do this for compilation because unreified methods with default params need to get actual global variable refs
  13290. return BfTypedValue(mBfIRBuilder->CreateConstNull(), fieldInstance->GetResolvedType(), true);
  13291. }
  13292. BfIRValue* globalValuePtr = NULL;
  13293. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  13294. {
  13295. globalValue = *globalValuePtr;
  13296. BF_ASSERT(globalValue);
  13297. auto globalVar = (BfGlobalVar*)mBfIRBuilder->GetConstant(globalValue);
  13298. if ((globalVar->mStreamId == -1) && (!mBfIRBuilder->mIgnoreWrites))
  13299. {
  13300. mBfIRBuilder->MapType(fieldInstance->mResolvedType);
  13301. mBfIRBuilder->CreateGlobalVariable(globalValue);
  13302. }
  13303. }
  13304. else
  13305. {
  13306. StringT<512> staticVarName;
  13307. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  13308. auto typeType = fieldInstance->GetResolvedType();
  13309. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  13310. {
  13311. typeType = typeType->GetUnderlyingType();
  13312. }
  13313. if (mIsComptimeModule)
  13314. {
  13315. mCompiler->mCeMachine->QueueStaticField(fieldInstance, staticVarName);
  13316. }
  13317. PopulateType(typeType);
  13318. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  13319. {
  13320. BfIRType irType = mBfIRBuilder->MapType(typeType);
  13321. if (fieldInstance->IsAppendedObject())
  13322. irType = mBfIRBuilder->MapTypeInst(typeType->ToTypeInstance());
  13323. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  13324. globalValue = mBfIRBuilder->CreateGlobalVariable(
  13325. irType,
  13326. false,
  13327. BfIRLinkageType_External,
  13328. BfIRValue(),
  13329. staticVarName,
  13330. IsThreadLocal(fieldInstance));
  13331. BF_ASSERT(globalValue);
  13332. mStaticFieldRefs[fieldInstance] = globalValue;
  13333. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  13334. }
  13335. }
  13336. auto type = fieldInstance->GetResolvedType();
  13337. if (type->IsValuelessType())
  13338. return BfTypedValue(globalValue, type);
  13339. if (fieldDef->mIsVolatile)
  13340. return BfTypedValue(globalValue, type, BfTypedValueKind_VolatileAddr);
  13341. return BfTypedValue(globalValue, type, !fieldDef->mIsConst && !fieldInstance->IsAppendedObject());
  13342. }
  13343. BfFieldInstance* BfModule::GetFieldInstance(BfTypeInstance* typeInst, int fieldIdx, const char* fieldName)
  13344. {
  13345. if (typeInst->IsDataIncomplete())
  13346. PopulateType(typeInst);
  13347. if (fieldIdx >= typeInst->mFieldInstances.mSize)
  13348. {
  13349. Fail(StrFormat("Invalid field data in type '%s'", TypeToString(typeInst).c_str()));
  13350. return 0;
  13351. }
  13352. return &typeInst->mFieldInstances[fieldIdx];
  13353. }
  13354. void BfModule::MarkUsingThis()
  13355. {
  13356. auto useMethodState = mCurMethodState;
  13357. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13358. {
  13359. useMethodState = useMethodState->mPrevMethodState;
  13360. }
  13361. if ((useMethodState != NULL) && (!useMethodState->mLocals.IsEmpty()))
  13362. {
  13363. auto localVar = useMethodState->mLocals[0];
  13364. if (localVar->mIsThis)
  13365. localVar->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13366. }
  13367. }
  13368. BfTypedValue BfModule::GetThis(bool markUsing)
  13369. {
  13370. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  13371. {
  13372. if (mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis)
  13373. return mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis;
  13374. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  13375. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  13376. if ((activeFrame != NULL) && (activeFrame->mFunction->mDbgInfo != NULL))
  13377. {
  13378. for (auto& dbgVar : activeFrame->mFunction->mDbgInfo->mVariables)
  13379. {
  13380. if (dbgVar.mName == "this")
  13381. return BfTypedValue(mBfIRBuilder->CreateConstAggCE(mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs), dbgVar.mType,
  13382. dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  13383. }
  13384. }
  13385. return BfTypedValue();
  13386. }
  13387. auto useMethodState = mCurMethodState;
  13388. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13389. {
  13390. useMethodState = useMethodState->mPrevMethodState;
  13391. }
  13392. if (useMethodState != NULL)
  13393. {
  13394. // Fake a 'this' for var field resolution
  13395. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  13396. {
  13397. auto thisType = mCurTypeInstance;
  13398. if (thisType->IsValueType())
  13399. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  13400. else
  13401. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  13402. }
  13403. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  13404. {
  13405. return BfTypedValue();
  13406. }
  13407. }
  13408. else
  13409. {
  13410. //TODO: Do we allow useMethodState to be NULL anymore?
  13411. return BfTypedValue();
  13412. }
  13413. // Check mixin state for 'this'
  13414. {
  13415. auto checkMethodState = mCurMethodState;
  13416. while (checkMethodState != NULL)
  13417. {
  13418. if (checkMethodState->mMixinState != NULL)
  13419. {
  13420. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  13421. if (thisValue.HasType())
  13422. {
  13423. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13424. if (!thisValue.mType->IsValueType())
  13425. thisValue = LoadValue(thisValue);
  13426. return thisValue;
  13427. }
  13428. }
  13429. checkMethodState = checkMethodState->mPrevMethodState;
  13430. }
  13431. }
  13432. auto curMethodInstance = mCurMethodInstance;
  13433. if (useMethodState->mMethodInstance != NULL)
  13434. curMethodInstance = useMethodState->mMethodInstance;
  13435. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  13436. {
  13437. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  13438. {
  13439. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  13440. if (constLocal.mIsThis)
  13441. {
  13442. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  13443. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  13444. }
  13445. }
  13446. return BfTypedValue();
  13447. }
  13448. if (useMethodState->mLocals.IsEmpty())
  13449. {
  13450. // 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
  13451. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  13452. return BfTypedValue();
  13453. }
  13454. auto thisLocal = useMethodState->mLocals[0];
  13455. BF_ASSERT(thisLocal->mIsThis);
  13456. bool preferValue = !IsTargetingBeefBackend();
  13457. if (!thisLocal->mAddr)
  13458. preferValue = true;
  13459. bool usedVal = false;
  13460. BfIRValue thisValue;
  13461. if ((preferValue) && (!thisLocal->mIsLowered))
  13462. {
  13463. thisValue = thisLocal->mValue;
  13464. usedVal = true;
  13465. }
  13466. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  13467. thisValue = thisLocal->mAddr;
  13468. else
  13469. thisValue = mBfIRBuilder->CreateAlignedLoad(thisLocal->mAddr, thisLocal->mResolvedType->mAlign);
  13470. if (markUsing)
  13471. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13472. if (useMethodState->mClosureState != NULL)
  13473. {
  13474. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  13475. if (closureTypeInst != NULL)
  13476. {
  13477. if (closureTypeInst->mFieldInstances.size() > 0)
  13478. {
  13479. auto& field = closureTypeInst->mFieldInstances[0];
  13480. auto fieldDef = field.GetFieldDef();
  13481. if (fieldDef->mName == "__this")
  13482. {
  13483. if (mCurMethodState->mClosureState->mCapturing)
  13484. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  13485. // This is a captured 'this'
  13486. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  13487. if (field.mResolvedType->IsRef())
  13488. {
  13489. auto refType = (BfRefType*)field.mResolvedType;
  13490. auto underlyingType = refType->GetUnderlyingType();
  13491. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  13492. }
  13493. if (field.mResolvedType->IsObject())
  13494. {
  13495. result = LoadValue(result);
  13496. result.mKind = BfTypedValueKind_ThisValue;
  13497. }
  13498. else
  13499. {
  13500. if (fieldDef->mIsReadOnly)
  13501. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  13502. else
  13503. result.mKind = BfTypedValueKind_ThisAddr;
  13504. }
  13505. return result;
  13506. }
  13507. }
  13508. return BfTypedValue();
  13509. }
  13510. if (useMethodState->mClosureState->mCapturing)
  13511. {
  13512. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  13513. if (thisType->IsValueType())
  13514. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  13515. else
  13516. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  13517. }
  13518. }
  13519. if (mCurMethodInstance == NULL)
  13520. return BfTypedValue();
  13521. auto localDef = useMethodState->mLocals[0];
  13522. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  13523. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  13524. {
  13525. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  13526. {
  13527. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  13528. }
  13529. if (localDef->mIsSplat)
  13530. {
  13531. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  13532. }
  13533. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  13534. }
  13535. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  13536. }
  13537. BfLocalVariable* BfModule::GetThisVariable()
  13538. {
  13539. if (mCurMethodState == NULL)
  13540. return NULL;
  13541. auto methodState = mCurMethodState->GetNonCaptureState();
  13542. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  13543. return methodState->mLocals[0];
  13544. return NULL;
  13545. }
  13546. bool BfModule::IsInGeneric()
  13547. {
  13548. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  13549. }
  13550. bool BfModule::InDefinitionSection()
  13551. {
  13552. if (mCurTypeInstance != NULL)
  13553. {
  13554. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  13555. return false;
  13556. }
  13557. return !IsInSpecializedSection();
  13558. }
  13559. bool BfModule::IsInSpecializedGeneric()
  13560. {
  13561. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  13562. return true;
  13563. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  13564. return false;
  13565. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  13566. }
  13567. bool BfModule::IsInSpecializedSection()
  13568. {
  13569. return IsInSpecializedGeneric() ||
  13570. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  13571. }
  13572. bool BfModule::IsInUnspecializedGeneric()
  13573. {
  13574. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  13575. return true;
  13576. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedType()))
  13577. return true;
  13578. return false;
  13579. }
  13580. //////////////////////////////////////////////////////////////////////////
  13581. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  13582. {
  13583. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  13584. if (type->IsValuelessType())
  13585. return mBfIRBuilder->GetFakeVal();
  13586. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  13587. if ((!doLifetimeEnd) && (WantsLifetimes()))
  13588. {
  13589. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  13590. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  13591. }
  13592. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  13593. auto typeOptions = GetTypeOptions();
  13594. if (typeOptions != NULL)
  13595. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  13596. // Local variable inits are implicitly handled in the Beef Backend
  13597. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  13598. {
  13599. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13600. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13601. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  13602. mBfIRBuilder->ClearDebugLocation(storeInst);
  13603. mBfIRBuilder->SetInsertPoint(prevBlock);
  13604. }
  13605. return allocaInst;
  13606. }
  13607. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  13608. {
  13609. while (localVar->mName.StartsWith('@'))
  13610. {
  13611. localVar->mNamePrefixCount++;
  13612. localVar->mName.Remove(0);
  13613. }
  13614. if (mCurMethodState->mLocals.mAllocSize == 0)
  13615. {
  13616. mCurMethodState->mLocals.Reserve(16);
  13617. mCurMethodState->mLocalVarSet.Reserve(16);
  13618. }
  13619. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  13620. mCurMethodState->mLocals.push_back(localVar);
  13621. BfLocalVarEntry* localVarEntryPtr;
  13622. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  13623. {
  13624. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  13625. localVarEntryPtr->mLocalVar = localVar;
  13626. }
  13627. }
  13628. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13629. {
  13630. if (localVarDef->mResolvedType->IsVar())
  13631. return;
  13632. if ((mBfIRBuilder->DbgHasInfo()) &&
  13633. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  13634. (mHasFullDebugInfo) &&
  13635. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  13636. {
  13637. auto varType = localVarDef->mResolvedType;
  13638. if (localVarDef->mResolvedType->IsValuelessType())
  13639. {
  13640. }
  13641. else
  13642. {
  13643. bool isByAddr = false;
  13644. auto diValue = localVarDef->mValue;
  13645. if (localVarDef->mConstValue)
  13646. diValue = localVarDef->mConstValue;
  13647. else if (localVarDef->mAddr)
  13648. {
  13649. diValue = localVarDef->mAddr;
  13650. isByAddr = true;
  13651. }
  13652. if (diValue.IsConst())
  13653. {
  13654. auto constant = mBfIRBuilder->GetConstant(diValue);
  13655. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  13656. {
  13657. // Ignore for now
  13658. return;
  13659. }
  13660. }
  13661. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  13662. bool didConstToMem = false;
  13663. bool isConstant = false;
  13664. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  13665. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13666. else if (localVarDef->mConstValue)
  13667. {
  13668. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  13669. isConstant =
  13670. (constant->mConstType < BfConstType_GlobalVar) ||
  13671. (constant->mConstType == BfConstType_AggZero) ||
  13672. (constant->mConstType == BfConstType_Agg);
  13673. if (isConstant)
  13674. {
  13675. if (localVarDef->mResolvedType->IsComposite())
  13676. {
  13677. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  13678. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  13679. // if (IsTargetingBeefBackend())
  13680. // {
  13681. // diValue = mBfIRBuilder->CreateAliasValue(constMem);
  13682. // didConstToMem = true;
  13683. //
  13684. // diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13685. // }
  13686. //else
  13687. {
  13688. isByAddr = true;
  13689. mBfIRBuilder->SaveDebugLocation();
  13690. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13691. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13692. mBfIRBuilder->ClearDebugLocation();
  13693. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  13694. auto addrVal = CreateAlloca(ptrType);
  13695. mBfIRBuilder->CreateStore(constMem, addrVal);
  13696. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13697. diValue = addrVal;
  13698. didConstToMem = true;
  13699. mBfIRBuilder->SetInsertPoint(prevBlock);
  13700. mBfIRBuilder->RestoreDebugLocation();
  13701. }
  13702. }
  13703. if (mCompiler->mOptions.IsCodeView())
  13704. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13705. }
  13706. }
  13707. if (!mBfIRBuilder->mIgnoreWrites)
  13708. {
  13709. if ((localVarDef->mIsStatic) && (localVarDef->mAddr) && (!localVarDef->mResolvedType->IsValuelessType()))
  13710. {
  13711. auto refType = CreateRefType(localVarDef->mResolvedType);
  13712. diType = mBfIRBuilder->DbgGetType(refType);
  13713. auto refAlloca = CreateAlloca(refType);
  13714. mBfIRBuilder->CreateStore(localVarDef->mAddr, refAlloca);
  13715. diValue = refAlloca;
  13716. }
  13717. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13718. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  13719. localVarDef->mDbgVarInst = diVariable;
  13720. if (mBfIRBuilder->HasDebugLocation())
  13721. {
  13722. if ((isConstant) && (!didConstToMem))
  13723. {
  13724. BfTypedValue result(localVarDef->mConstValue, localVarDef->mResolvedType);
  13725. FixValueActualization(result);
  13726. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(result.mValue, diVariable);
  13727. }
  13728. else
  13729. {
  13730. if ((IsTargetingBeefBackend()) && (doAliasValue) && (!mIsComptimeModule))
  13731. {
  13732. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  13733. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  13734. }
  13735. if (isByAddr)
  13736. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  13737. else if (diValue)
  13738. {
  13739. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  13740. }
  13741. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  13742. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  13743. }
  13744. }
  13745. }
  13746. }
  13747. }
  13748. }
  13749. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13750. {
  13751. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  13752. {
  13753. if ((!localVarDef->mValue.IsConst()) &&
  13754. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  13755. {
  13756. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  13757. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  13758. }
  13759. }
  13760. if (addDebugInfo)
  13761. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  13762. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  13763. DoAddLocalVariable(localVarDef);
  13764. auto rootMethodState = mCurMethodState->GetRootMethodState();
  13765. if (localVarDef->mLocalVarId == -1)
  13766. {
  13767. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  13768. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  13769. }
  13770. bool checkLocal = true;
  13771. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  13772. {
  13773. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(mCurMethodInstance->mMethodDef->mMethodDeclaration))
  13774. checkLocal = false;
  13775. }
  13776. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!mIsComptimeModule) && (checkLocal))
  13777. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  13778. if (((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL)) && (checkLocal))
  13779. {
  13780. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  13781. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL) && (rootMethodState->mMethodInstance != NULL) && (!mIsComptimeModule))
  13782. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  13783. }
  13784. return localVarDef;
  13785. }
  13786. void BfModule::CreateDIRetVal()
  13787. {
  13788. if (!WantsDebugInfo())
  13789. return;
  13790. /*if (!mCurMethodState->mRetVal)
  13791. {
  13792. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  13793. return;
  13794. }*/
  13795. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  13796. {
  13797. BfType* dbgType = mCurMethodInstance->mReturnType;
  13798. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  13799. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13800. {
  13801. BF_ASSERT(mCurMethodState->mRetValAddr);
  13802. dbgType = CreatePointerType(dbgType);
  13803. dbgValue = mCurMethodState->mRetValAddr;
  13804. }
  13805. else
  13806. {
  13807. BF_ASSERT(!mCurMethodState->mRetValAddr);
  13808. }
  13809. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13810. "@return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  13811. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  13812. }
  13813. }
  13814. BfTypedValue BfModule::CreateTuple(const Array<BfTypedValue>& values, const Array<String>& fieldNames)
  13815. {
  13816. BfTypeVector fieldTypes;
  13817. for (auto arg : values)
  13818. fieldTypes.Add(arg.mType);
  13819. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  13820. auto tupleTypedValue = BfTypedValue(CreateAlloca(tupleType), tupleType, true);
  13821. for (int fieldIdx = 0; fieldIdx < tupleType->mFieldInstances.size(); fieldIdx++)
  13822. {
  13823. auto& fieldInstance = tupleType->mFieldInstances[fieldIdx];
  13824. if (fieldInstance.mDataIdx <= 0)
  13825. continue;
  13826. auto typedVal = values[fieldIdx];
  13827. typedVal = LoadOrAggregateValue(typedVal);
  13828. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, mBfIRBuilder->CreateInBoundsGEP(tupleTypedValue.mValue, 0, fieldInstance.mDataIdx), typedVal.mType->mAlign);
  13829. }
  13830. return tupleTypedValue;
  13831. }
  13832. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  13833. {
  13834. if (variableDef->mName.IsEmpty())
  13835. return;
  13836. BfLocalVarEntry* localVarEntryPtr = NULL;
  13837. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  13838. {
  13839. auto checkLocal = localVarEntryPtr->mLocalVar;
  13840. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  13841. {
  13842. BfError* error;
  13843. if (checkLocal->mIsImplicitParam)
  13844. return; // Ignore 'redefinition'
  13845. if (checkLocal->IsParam())
  13846. {
  13847. if (variableDef->IsParam())
  13848. error = Fail(StrFormat("A parameter named '%s' has already been declared", variableDef->mName.c_str()), variableDef->mNameNode);
  13849. else
  13850. error = Fail(StrFormat("The name '%s' is already used by a parameter. Consider declaring 'var %s;' if you wish to make a mutable copy of that parameter.", variableDef->mName.c_str(), variableDef->mName.c_str()), variableDef->mNameNode);
  13851. }
  13852. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  13853. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13854. else
  13855. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13856. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  13857. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  13858. return;
  13859. }
  13860. }
  13861. }
  13862. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  13863. {
  13864. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  13865. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  13866. {
  13867. if (tokenNode->GetToken() == BfToken_Colon)
  13868. {
  13869. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  13870. {
  13871. Fail("Cannot access method scope across deferred block boundary", scopeName);
  13872. return NULL;
  13873. }
  13874. return &mCurMethodState->mHeadScope;
  13875. }
  13876. else if (tokenNode->GetToken() == BfToken_Mixin)
  13877. {
  13878. if (fromMixinState == NULL)
  13879. {
  13880. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  13881. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  13882. return mCurMethodState->mCurScope;
  13883. }
  13884. fromMixinState->mUsedInvocationScope = true;
  13885. return fromMixinState->mTargetScope;
  13886. }
  13887. else if (tokenNode->GetToken() == BfToken_New)
  13888. return NULL;
  13889. }
  13890. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  13891. {
  13892. auto findLabel = scopeName->ToString();
  13893. bool crossedDeferredBlock = false;
  13894. auto checkScope = mCurMethodState->mCurScope;
  13895. while (checkScope != NULL)
  13896. {
  13897. if (checkScope->mIsDeferredBlock)
  13898. crossedDeferredBlock = true;
  13899. if (checkScope->mLabel == findLabel)
  13900. {
  13901. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  13902. {
  13903. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  13904. return NULL;
  13905. }
  13906. return checkScope;
  13907. }
  13908. checkScope = checkScope->mPrevScope;
  13909. }
  13910. if (!inMixinDecl)
  13911. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  13912. }
  13913. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  13914. {
  13915. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  13916. }
  13917. return mCurMethodState->mCurScope;
  13918. }
  13919. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  13920. {
  13921. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  13922. }
  13923. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  13924. {
  13925. auto scopeData = FindScope(scopeName, false);
  13926. if (scopeData == NULL)
  13927. return NULL;
  13928. int scopeDepth = scopeData->GetDepth();
  13929. // Find the first break data that is at or below the depth of our requested scope
  13930. auto breakData = mCurMethodState->mBreakData;
  13931. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  13932. {
  13933. if (breakData->mScope->mIsConditional)
  13934. return NULL;
  13935. breakData = breakData->mPrevBreakData;
  13936. }
  13937. return breakData;
  13938. }
  13939. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  13940. {
  13941. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  13942. if (!IsTargetingBeefBackend())
  13943. return;
  13944. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  13945. {
  13946. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13947. }
  13948. }
  13949. void BfModule::ClearLifetimeEnds()
  13950. {
  13951. auto scopeData = mCurMethodState->mCurScope;
  13952. while (scopeData != NULL)
  13953. {
  13954. scopeData->mDeferredLifetimeEnds.Clear();
  13955. scopeData = scopeData->mPrevScope;
  13956. }
  13957. }
  13958. bool BfModule::WantsDebugInfo()
  13959. {
  13960. if ((mCurMethodInstance != NULL) &&
  13961. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  13962. return false;
  13963. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  13964. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  13965. }
  13966. BfTypeOptions* BfModule::GetTypeOptions()
  13967. {
  13968. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  13969. return mCurMethodState->mMethodTypeOptions;
  13970. if (mCurMethodInstance == NULL)
  13971. return NULL;
  13972. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  13973. }
  13974. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  13975. {
  13976. BfReflectKind reflectKind = BfReflectKind_None;
  13977. if (attrType->mCustomAttributes != NULL)
  13978. {
  13979. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  13980. {
  13981. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  13982. {
  13983. for (auto& prop : customAttr.mSetProperties)
  13984. {
  13985. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  13986. if (propDef->mName == "ReflectUser")
  13987. {
  13988. if (prop.mParam.mValue.IsConst())
  13989. {
  13990. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  13991. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  13992. }
  13993. }
  13994. }
  13995. // Check for Flags arg
  13996. if (customAttr.mCtorArgs.size() < 2)
  13997. continue;
  13998. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  13999. if (constant == NULL)
  14000. continue;
  14001. if (constant->mTypeCode == BfTypeCode_Boolean)
  14002. continue;
  14003. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  14004. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  14005. }
  14006. }
  14007. }
  14008. return reflectKind;
  14009. }
  14010. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  14011. {
  14012. auto checkTypeInstance = typeInstance;
  14013. while (checkTypeInstance != NULL)
  14014. {
  14015. if (checkTypeInstance->mCustomAttributes != NULL)
  14016. {
  14017. auto checkReflectKind = BfReflectKind_None;
  14018. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  14019. {
  14020. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  14021. {
  14022. if (customAttr.mCtorArgs.size() > 0)
  14023. {
  14024. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  14025. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  14026. }
  14027. else
  14028. {
  14029. checkReflectKind = BfReflectKind_All;
  14030. }
  14031. }
  14032. else
  14033. {
  14034. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  14035. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  14036. }
  14037. }
  14038. if ((checkTypeInstance == typeInstance) ||
  14039. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  14040. {
  14041. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  14042. }
  14043. }
  14044. for (auto ifaceEntry : typeInstance->mInterfaces)
  14045. {
  14046. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  14047. {
  14048. auto iface = ifaceEntry.mInterfaceType;
  14049. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  14050. if (customAttr != NULL)
  14051. {
  14052. for (auto& prop : customAttr->mSetProperties)
  14053. {
  14054. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  14055. if (propDef->mName == "ReflectImplementer")
  14056. {
  14057. if (prop.mParam.mValue.IsConst())
  14058. {
  14059. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  14060. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  14061. }
  14062. }
  14063. }
  14064. }
  14065. }
  14066. }
  14067. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  14068. }
  14069. return reflectKind;
  14070. }
  14071. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  14072. {
  14073. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14074. while (checkScope != NULL)
  14075. {
  14076. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  14077. return true;
  14078. if (checkScope == scope)
  14079. break;
  14080. checkScope = checkScope->mPrevScope;
  14081. }
  14082. return false;
  14083. }
  14084. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  14085. {
  14086. // Is there anything we need to do here?
  14087. if (mBfIRBuilder->mIgnoreWrites)
  14088. {
  14089. // Just visit deferred blocks
  14090. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14091. while (checkScope != NULL)
  14092. {
  14093. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14094. while (deferredCallEntry != NULL)
  14095. {
  14096. if (deferredCallEntry->mDeferredBlock != NULL)
  14097. {
  14098. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14099. if (checkScope == &mCurMethodState->mHeadScope)
  14100. CreateRetValLocal();
  14101. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry->mEmitRefNode);
  14102. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  14103. }
  14104. deferredCallEntry = deferredCallEntry->mNext;
  14105. }
  14106. if (checkScope == scopeData)
  14107. break;
  14108. checkScope = checkScope->mPrevScope;
  14109. }
  14110. return;
  14111. }
  14112. // Why did we want to do SetIllegalSrcPos here?
  14113. // Don't we always want to step onto these instances?
  14114. // Find a case where we don't and perhaps only do it there.
  14115. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  14116. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  14117. //SetIllegalSrcPos();
  14118. bool setSrcPos = false;
  14119. bool wantsNop = true;
  14120. BfAstNode* deferCloseNode = NULL;
  14121. if (mCurMethodState->mInPostReturn)
  14122. {
  14123. // These won't get used, they are post-return
  14124. return;
  14125. }
  14126. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  14127. BfScopeData* scopeJumpBlock = NULL;
  14128. bool hadExtraDeferredLifetimeEnds = false;
  14129. auto _FlushLifetimeEnds = [&]()
  14130. {
  14131. for (auto lifetimeEnd : deferredLifetimeEnds)
  14132. {
  14133. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14134. mBfIRBuilder->ClearDebugLocation_Last();
  14135. }
  14136. deferredLifetimeEnds.clear();
  14137. };
  14138. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14139. while (checkScope != NULL)
  14140. {
  14141. if (checkScope->mCloseNode != NULL)
  14142. deferCloseNode = checkScope->mCloseNode;
  14143. if (doneBlock)
  14144. {
  14145. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  14146. for (auto& checkHandler : checkScope->mDeferredHandlers)
  14147. {
  14148. if (checkHandler.mDoneBlock == doneBlock)
  14149. {
  14150. scopeJumpBlock = checkScope;
  14151. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  14152. mBfIRBuilder->ClearDebugLocation_Last();
  14153. _FlushLifetimeEnds();
  14154. break;
  14155. }
  14156. }
  14157. if (scopeJumpBlock != NULL)
  14158. break;
  14159. }
  14160. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  14161. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  14162. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  14163. if (hasWork)
  14164. {
  14165. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  14166. if (deferCloseNode != NULL)
  14167. {
  14168. UpdateSrcPos(deferCloseNode);
  14169. }
  14170. if (checkScope == &mCurMethodState->mHeadScope)
  14171. CreateRetValLocal();
  14172. if (doneBlock)
  14173. {
  14174. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  14175. String blockName = "deferredCalls";
  14176. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  14177. BfDeferredHandler deferredHandler;
  14178. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  14179. {
  14180. mBfIRBuilder->SaveDebugLocation();
  14181. mBfIRBuilder->ClearDebugLocation();
  14182. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  14183. mBfIRBuilder->RestoreDebugLocation();
  14184. }
  14185. else
  14186. {
  14187. // Definitely chain
  14188. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  14189. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  14190. mBfIRBuilder->ClearDebugLocation_Last();
  14191. _FlushLifetimeEnds();
  14192. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  14193. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  14194. }
  14195. deferredHandler.mDoneBlock = doneBlock;
  14196. if (!mBfIRBuilder->mIgnoreWrites)
  14197. checkScope->mDeferredHandlers.push_back(deferredHandler);
  14198. if (checkScope == &mCurMethodState->mHeadScope)
  14199. {
  14200. if (!mCurMethodState->mDIRetVal)
  14201. {
  14202. // 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
  14203. // be scoped to the physical method
  14204. /*if (deferCloseNode != NULL)
  14205. {
  14206. UpdateSrcPos(deferCloseNode);
  14207. }*/
  14208. CreateDIRetVal();
  14209. }
  14210. }
  14211. if (checkScope != mCurMethodState->mTailScope)
  14212. {
  14213. if (deferredHandler.mHandlerBlock.IsFake())
  14214. {
  14215. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14216. }
  14217. if (!mBfIRBuilder->mIgnoreWrites)
  14218. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  14219. }
  14220. }
  14221. HashSet<BfDeferredCallEntry*> handledSet;
  14222. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14223. while (deferredCallEntry != NULL)
  14224. {
  14225. BfDeferredCallEmitState deferredCallEmitState;
  14226. deferredCallEmitState.mCloseNode = deferCloseNode;
  14227. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  14228. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  14229. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14230. if (deferCloseNode != NULL)
  14231. {
  14232. UpdateSrcPos(deferCloseNode);
  14233. }
  14234. if (wantsNop)
  14235. EmitEnsureInstructionAt();
  14236. wantsNop = false;
  14237. if (deferredCallEntry->mDeferredBlock != NULL)
  14238. {
  14239. BfDeferredCallEntry** entryPtr = NULL;
  14240. if (!handledSet.TryAdd(deferredCallEntry, &entryPtr))
  14241. {
  14242. // Already handled, can happen if we defer again within the block
  14243. deferredCallEntry = deferredCallEntry->mNext;
  14244. continue;
  14245. }
  14246. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  14247. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14248. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  14249. {
  14250. // The list changed, start over and ignore anything we've already handled
  14251. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14252. }
  14253. else
  14254. deferredCallEntry = deferredCallEntry->mNext;
  14255. }
  14256. else
  14257. {
  14258. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14259. deferredCallEntry = deferredCallEntry->mNext;
  14260. }
  14261. }
  14262. if (checkScope->mSavedStack)
  14263. {
  14264. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  14265. if (mCurMethodState->mDynStackRevIdx)
  14266. {
  14267. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  14268. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  14269. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  14270. }
  14271. }
  14272. }
  14273. if (!checkScope->mIsScopeHead)
  14274. {
  14275. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  14276. if (!IsTargetingBeefBackend())
  14277. {
  14278. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14279. {
  14280. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14281. }
  14282. }
  14283. else
  14284. {
  14285. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14286. {
  14287. deferredLifetimeEnds.Add(lifetimeEnd);
  14288. }
  14289. }
  14290. }
  14291. if (checkScope == scopeData)
  14292. break;
  14293. checkScope = checkScope->mPrevScope;
  14294. }
  14295. if ((doneBlock) && (scopeJumpBlock == NULL))
  14296. {
  14297. mBfIRBuilder->CreateBr(doneBlock);
  14298. mBfIRBuilder->ClearDebugLocation_Last();
  14299. }
  14300. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  14301. // may have been created when other scope lifetimes were available
  14302. _FlushLifetimeEnds();
  14303. // Emit lifetimeEnds after the branch for Beef
  14304. /*if (IsTargetingBeefBackend())
  14305. {
  14306. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  14307. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14308. while (checkScope != NULL)
  14309. {
  14310. if (checkScope == scopeJumpBlock)
  14311. break;
  14312. if (!checkScope->mIsScopeHead)
  14313. {
  14314. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14315. {
  14316. if (needsEnsureInst)
  14317. {
  14318. needsEnsureInst = false;
  14319. }
  14320. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14321. }
  14322. }
  14323. if (checkScope == scopeData)
  14324. break;
  14325. checkScope = checkScope->mPrevScope;
  14326. }
  14327. }*/
  14328. }
  14329. void BfModule::MarkScopeLeft(BfScopeData* scopeData, bool isNoReturn)
  14330. {
  14331. if ((mCurMethodState->mDeferredLocalAssignData != NULL) && (!isNoReturn))
  14332. {
  14333. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  14334. while (deferredLocalAssignData != NULL)
  14335. {
  14336. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  14337. break;
  14338. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  14339. deferredLocalAssignData->mIsUnconditional = false;
  14340. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  14341. }
  14342. }
  14343. // When we leave a scope, mark those as assigned for deferred assignment purposes
  14344. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  14345. {
  14346. auto localDef = mCurMethodState->mLocals[localIdx];
  14347. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  14348. {
  14349. bool hadAssignment = false;
  14350. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  14351. {
  14352. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  14353. if (entry.mLocalVar == localDef)
  14354. hadAssignment = true;
  14355. }
  14356. if (!hadAssignment)
  14357. {
  14358. if (!isNoReturn)
  14359. localDef->mHadExitBeforeAssign = true;
  14360. mCurMethodState->LocalDefined(localDef);
  14361. }
  14362. }
  14363. }
  14364. }
  14365. void BfModule::CreateReturn(BfIRValue val)
  14366. {
  14367. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14368. {
  14369. // Store to sret
  14370. BF_ASSERT(val);
  14371. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14372. mBfIRBuilder->CreateRetVoid();
  14373. return;
  14374. }
  14375. if (mCurMethodInstance->mReturnType->IsVar())
  14376. return;
  14377. if (mCurMethodInstance->mReturnType->IsValuelessType())
  14378. {
  14379. mBfIRBuilder->CreateRetVoid();
  14380. return;
  14381. }
  14382. if (mCurMethodInstance->mReturnType->IsStruct())
  14383. {
  14384. BfTypeCode loweredReturnType = BfTypeCode_None;
  14385. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  14386. if (!mIsComptimeModule)
  14387. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  14388. if (loweredReturnType != BfTypeCode_None)
  14389. {
  14390. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  14391. mBfIRBuilder->CreateStore(val, retVal);
  14392. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  14393. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  14394. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  14395. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  14396. mBfIRBuilder->CreateRet(loadedReturnValue);
  14397. return;
  14398. }
  14399. }
  14400. BF_ASSERT(val);
  14401. mBfIRBuilder->CreateRet(val);
  14402. }
  14403. void BfModule::EmitReturn(const BfTypedValue& val)
  14404. {
  14405. if (mCurMethodState->mIRExitBlock)
  14406. {
  14407. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  14408. {
  14409. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  14410. {
  14411. if ((mCurMethodState->mRetValAddr) || (mCurMethodState->mRetVal))
  14412. {
  14413. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  14414. if (!mCurMethodState->mRetVal)
  14415. retVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetValAddr, mCurMethodInstance->mReturnType->mAlign);
  14416. mBfIRBuilder->CreateAlignedStore(val.mValue, retVal, mCurMethodInstance->mReturnType->mAlign);
  14417. }
  14418. else if (mIsComptimeModule)
  14419. {
  14420. if (!val.mType->IsValuelessType())
  14421. mBfIRBuilder->CreateSetRet(val.mValue, val.mType->mTypeId);
  14422. else
  14423. mBfIRBuilder->CreateSetRet(BfIRValue(), val.mType->mTypeId);
  14424. }
  14425. else
  14426. {
  14427. // Just ignore
  14428. BF_ASSERT(mCurMethodInstance->mReturnType->IsVar());
  14429. }
  14430. }
  14431. }
  14432. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14433. }
  14434. else
  14435. {
  14436. EmitDeferredScopeCalls(false, NULL);
  14437. if (val)
  14438. {
  14439. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14440. }
  14441. }
  14442. mCurMethodState->SetHadReturn(true);
  14443. mCurMethodState->mLeftBlockUncond = true;
  14444. }
  14445. void BfModule::EmitDefaultReturn()
  14446. {
  14447. if (mCurMethodState->mInDeferredBlock)
  14448. return;
  14449. if (mCurMethodState->mIRExitBlock)
  14450. {
  14451. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14452. }
  14453. else
  14454. {
  14455. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mReturnType->IsVar()))
  14456. {
  14457. // Ignore
  14458. }
  14459. else if (mCurMethodInstance->mReturnType->IsVoid())
  14460. mBfIRBuilder->CreateRetVoid();
  14461. else if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == -1))
  14462. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  14463. }
  14464. mCurMethodState->SetHadReturn(true);
  14465. mCurMethodState->mLeftBlockUncond = true;
  14466. }
  14467. void BfModule::AssertErrorState()
  14468. {
  14469. if (mIgnoreErrors)
  14470. return;
  14471. if (mHadBuildError)
  14472. return;
  14473. if (mCurTypeInstance != NULL)
  14474. {
  14475. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  14476. return;
  14477. }
  14478. if (mCurMethodInstance != NULL)
  14479. {
  14480. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  14481. return;
  14482. if (mCurMethodInstance->mHasFailed)
  14483. return;
  14484. }
  14485. // We want the module to be marked as failed even if it's just an error in the parser
  14486. if (mCurMethodInstance != NULL)
  14487. mCurMethodInstance->mHasFailed = true;
  14488. mHadBuildError = true;
  14489. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  14490. if (mCurTypeInstance != NULL)
  14491. {
  14492. if (mCurTypeInstance->mTypeFailed)
  14493. return;
  14494. if ((mCurTypeInstance->mTypeDef->GetDefinition()->mSource != NULL) && (mCurTypeInstance->mTypeDef->GetDefinition()->mSource->mParsingFailed))
  14495. return;
  14496. }
  14497. if (mCurMethodInstance != NULL)
  14498. {
  14499. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) &&
  14500. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14501. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14502. return;
  14503. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) &&
  14504. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14505. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14506. return;
  14507. }
  14508. if (mCompiler->IsAutocomplete())
  14509. return;
  14510. if (mCompiler->mPassInstance->HasFailed())
  14511. return;
  14512. InternalError("Compiler in invalid state but AssertErrorState failed to prior error");
  14513. }
  14514. void BfModule::AssertParseErrorState()
  14515. {
  14516. if (mCompiler->mRevision == 1)
  14517. AssertErrorState();
  14518. }
  14519. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  14520. {
  14521. BF_ASSERT(delegateType->IsDelegateOrFunction());
  14522. auto typeInst = delegateType->ToTypeInstance();
  14523. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  14524. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  14525. if (invokeMethodInstance == NULL)
  14526. return GetPrimitiveType(BfTypeCode_Var);
  14527. return invokeMethodInstance->mReturnType;
  14528. }
  14529. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  14530. {
  14531. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  14532. }
  14533. void BfModule::CreateDelegateInvokeMethod()
  14534. {
  14535. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  14536. //mBfIRBuilder->ClearDebugLocation();
  14537. SetIllegalSrcPos();
  14538. auto typeInstance = mCurTypeInstance;
  14539. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  14540. SizedArray<BfIRType, 4> staticParamTypes;
  14541. SizedArray<BfIRValue, 4> staticFuncArgs;
  14542. SizedArray<BfIRValue, 4> memberFuncArgs;
  14543. auto multicastDelegateType = typeInstance->mBaseType;
  14544. if (multicastDelegateType->mFieldInstances.size() != 2)
  14545. {
  14546. AssertErrorState();
  14547. return;
  14548. }
  14549. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  14550. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  14551. auto fieldVal = mBfIRBuilder->CreateAlignedLoad(fieldPtr, mSystem->mPtrSize);
  14552. BfExprEvaluator exprEvaluator(this);
  14553. SizedArray<BfIRType, 8> origParamTypes;
  14554. BfIRType origReturnType;
  14555. BfIRType staticReturnType;
  14556. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  14557. if (mCurMethodInstance->mReturnType->IsValueType())
  14558. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  14559. if ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() != 0))
  14560. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14561. int thisIdx = 0;
  14562. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14563. {
  14564. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  14565. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14566. }
  14567. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14568. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14569. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == 0))
  14570. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14571. mCurMethodInstance->GetIRFunctionInfo(this, staticReturnType, staticParamTypes, true);
  14572. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14573. {
  14574. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  14575. exprEvaluator.PushArg(localVal, staticFuncArgs);
  14576. exprEvaluator.PushArg(localVal, memberFuncArgs);
  14577. }
  14578. auto staticFunc = mBfIRBuilder->CreateFunctionType(staticReturnType, staticParamTypes, false);
  14579. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  14580. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  14581. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  14582. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  14583. auto doneBB = mBfIRBuilder->CreateBlock("done");
  14584. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  14585. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  14586. BfIRValue nonStaticResult;
  14587. BfIRValue staticResult;
  14588. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  14589. auto trueEndBB = trueBB;
  14590. /// Non-static invocation
  14591. {
  14592. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  14593. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  14594. mBfIRBuilder->SetInsertPoint(trueBB);
  14595. BfIRValue numVal;
  14596. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule) && (mCompiler->mSystem->mPtrSize == 8))
  14597. {
  14598. numVal = mBfIRBuilder->CreatePtrToInt(fieldVal, BfTypeCode_UInt64);
  14599. auto andVal = mBfIRBuilder->CreateAnd(numVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)~0x8000000000000000ULL));
  14600. fieldVal = mBfIRBuilder->CreateIntToPtr(andVal, mBfIRBuilder->MapType(mContext->mBfObjectType));
  14601. }
  14602. if ((WantsObjectAccessCheck(mContext->mBfObjectType) && (mCompiler->mSystem->mPtrSize == 8)))
  14603. {
  14604. auto oacDoBB = mBfIRBuilder->CreateBlock("oac.do", true);
  14605. auto oacDoneBB = mBfIRBuilder->CreateBlock("oac.done");
  14606. auto checkGTE = mBfIRBuilder->CreateCmpGTE(numVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)0x8000000000000000ULL), false);
  14607. mBfIRBuilder->CreateCondBr(checkGTE, oacDoBB, oacDoneBB);
  14608. mBfIRBuilder->SetInsertPoint(oacDoBB);
  14609. mBfIRBuilder->CreateObjectAccessCheck(fieldVal, !IsOptimized());
  14610. mBfIRBuilder->CreateBr(oacDoneBB);
  14611. mBfIRBuilder->AddBlock(oacDoneBB);
  14612. mBfIRBuilder->SetInsertPoint(oacDoneBB);
  14613. trueEndBB = oacDoneBB;
  14614. }
  14615. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  14616. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14617. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  14618. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14619. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  14620. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14621. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  14622. if (callingConv != BfIRCallingConv_CDecl)
  14623. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  14624. mCurMethodState->SetHadReturn(false);
  14625. mCurMethodState->mLeftBlockUncond = false;
  14626. mCurMethodState->mLeftBlockCond = false;
  14627. mBfIRBuilder->CreateBr(doneBB);
  14628. }
  14629. // Static invocation
  14630. {
  14631. mBfIRBuilder->AddBlock(falseBB);
  14632. mBfIRBuilder->SetInsertPoint(falseBB);
  14633. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14634. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  14635. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14636. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  14637. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14638. {
  14639. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  14640. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  14641. }
  14642. // We had a sret for the non-static but no sret for the static (because we have a lowered return type there)
  14643. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1) && (mCurMethodInstance->GetStructRetIdx(true) == -1))
  14644. {
  14645. auto sretToType = mBfIRBuilder->GetPointerTo(staticReturnType);
  14646. auto sretCastedPtr = mBfIRBuilder->CreateBitCast(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), sretToType);
  14647. mBfIRBuilder->CreateStore(staticResult, sretCastedPtr);
  14648. }
  14649. if (callingConv == BfIRCallingConv_ThisCall)
  14650. callingConv = BfIRCallingConv_CDecl;
  14651. if (callingConv != BfIRCallingConv_CDecl)
  14652. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  14653. mCurMethodState->SetHadReturn(false);
  14654. mCurMethodState->mLeftBlockUncond = false;
  14655. mCurMethodState->mLeftBlockCond = false;
  14656. mBfIRBuilder->CreateBr(doneBB);
  14657. }
  14658. mBfIRBuilder->AddBlock(doneBB);
  14659. mBfIRBuilder->SetInsertPoint(doneBB);
  14660. if (mCurMethodInstance->mReturnType->IsVar())
  14661. {
  14662. // Do nothing
  14663. }
  14664. else if ((mCurMethodInstance->mReturnType->IsValuelessType()) ||
  14665. ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1)))
  14666. {
  14667. mBfIRBuilder->CreateRetVoid();
  14668. }
  14669. else
  14670. {
  14671. BfIRType loweredIRReturnType;
  14672. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14673. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14674. if ((!mIsComptimeModule) && (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2)))
  14675. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  14676. else
  14677. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  14678. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  14679. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueEndBB);
  14680. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  14681. mBfIRBuilder->CreateRet(phi);
  14682. }
  14683. }
  14684. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  14685. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  14686. {
  14687. auto typeDef = typeInstance->mTypeDef;
  14688. auto methodDeclaration = methodDef->mMethodDeclaration;
  14689. if (!mCompiler->mIsResolveOnly)
  14690. return true;
  14691. if (typeInstance->IsGenericTypeInstance())
  14692. {
  14693. // We only really want to process the unspecialized type for autocompletion
  14694. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  14695. return false;
  14696. }
  14697. BfAstNode* checkNode = methodDeclaration;
  14698. if (methodDeclaration == NULL)
  14699. checkNode = methodDef->mBody;
  14700. if ((!mCompiler->mResolvePassData->mParsers.IsEmpty()) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParsers[0])))
  14701. {
  14702. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  14703. return true;
  14704. }
  14705. return false;
  14706. }
  14707. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  14708. {
  14709. methodInst->mAppendAllocAlign = 1;
  14710. }
  14711. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args, bool force)
  14712. {
  14713. BP_ZONE("BfModule::TryConstCalcAppend");
  14714. BF_ASSERT(methodInst->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  14715. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (!force))
  14716. return BfTypedValue();
  14717. // We want to regenerate all ctor calls when the method internals change
  14718. {
  14719. auto checkTypeInst = methodInst->GetOwner();
  14720. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  14721. {
  14722. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  14723. checkTypeInst = GetBaseType(checkTypeInst);
  14724. }
  14725. }
  14726. if (!methodInst->mMayBeConst)
  14727. return BfTypedValue();
  14728. // Do we need to iterate in order to resolve mAppendAllocAlign?
  14729. bool isFirstRun = methodInst->mEndingAppendAllocAlign < 0;
  14730. bool wasAllConst = true;
  14731. int argIdx = 0;
  14732. int paramIdx = 0;
  14733. while (true)
  14734. {
  14735. if (argIdx >= (int)args.size())
  14736. break;
  14737. auto paramType = methodInst->GetParamType(paramIdx);
  14738. PopulateType(paramType);
  14739. int argCount = 0;
  14740. if (!paramType->IsValuelessType())
  14741. {
  14742. if ((!mIsComptimeModule) && (methodInst->GetParamIsSplat(paramIdx)))
  14743. argCount = paramType->GetSplatCount();
  14744. else
  14745. argCount = 1;
  14746. for (int argOfs = 0; argOfs < argCount; argOfs++)
  14747. {
  14748. auto arg = args[argIdx + argOfs];
  14749. if (!arg.IsConst())
  14750. {
  14751. wasAllConst = false;
  14752. if (!isFirstRun)
  14753. {
  14754. auto& param = methodInst->mParams[argIdx];
  14755. if (param.mReferencedInConstPass)
  14756. {
  14757. // If this param is required as part of the const calculation then
  14758. // we require that it be const...
  14759. return BfTypedValue();
  14760. }
  14761. }
  14762. }
  14763. }
  14764. }
  14765. paramIdx++;
  14766. argIdx += argCount;
  14767. }
  14768. auto methodDef = methodInst->mMethodDef;
  14769. auto methodDecl = methodDef->GetMethodDeclaration();
  14770. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14771. if (methodDeclBlock == NULL)
  14772. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  14773. BfTypedValue constValue;
  14774. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  14775. auto checkState = mCurMethodState->mConstResolveState;
  14776. while (checkState != NULL)
  14777. {
  14778. if (checkState->mMethodInstance == methodInst)
  14779. {
  14780. return BfTypedValue();
  14781. }
  14782. checkState = checkState->mPrevConstResolveState;
  14783. }
  14784. //auto accumValue = GetConstValue(0);
  14785. bool failed = false;
  14786. //
  14787. {
  14788. BfConstResolveState constResolveState;
  14789. constResolveState.mMethodInstance = methodInst;
  14790. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  14791. constResolveState.mInCalcAppend = true;
  14792. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14793. BfMethodState methodState;
  14794. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  14795. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  14796. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  14797. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  14798. methodState.mConstResolveState = &constResolveState;
  14799. int argIdx = 0;
  14800. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14801. {
  14802. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  14803. continue;
  14804. auto paramType = methodInst->GetParamType(paramIdx);
  14805. // Fix this after we allow structs to be consts
  14806. //BF_ASSERT(!paramType->IsSplattable());
  14807. BfLocalVariable* localVar = new BfLocalVariable();
  14808. localVar->mName = methodInst->GetParamName(paramIdx);
  14809. localVar->mResolvedType = paramType;
  14810. localVar->mConstValue = args[argIdx];
  14811. localVar->mParamIdx = paramIdx;
  14812. AddLocalVariableDef(localVar);
  14813. argIdx++;
  14814. }
  14815. AppendAllocVisitor appendAllocVisitor;
  14816. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  14817. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  14818. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  14819. if (baseCtorAppendValue)
  14820. {
  14821. if (baseCtorAppendValue.mValue.IsFake())
  14822. appendAllocVisitor.mFailed = true;
  14823. else
  14824. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  14825. }
  14826. appendAllocVisitor.mModule = this;
  14827. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14828. if (constResolveState.mFailed)
  14829. appendAllocVisitor.mFailed = true;
  14830. if (!appendAllocVisitor.mFailed)
  14831. constValue = appendAllocVisitor.mConstAccum;
  14832. if (isFirstRun)
  14833. {
  14834. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  14835. if (mCurMethodInstance->mAppendAllocAlign <= 0)
  14836. mCurMethodInstance->mAppendAllocAlign = 1;
  14837. }
  14838. if (isFirstRun)
  14839. {
  14840. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14841. {
  14842. auto localVar = mCurMethodState->mLocals[paramIdx];
  14843. if (localVar->mReadFromId != -1)
  14844. {
  14845. auto& param = methodInst->mParams[paramIdx];
  14846. param.mReferencedInConstPass = true;
  14847. }
  14848. }
  14849. }
  14850. }
  14851. mBfIRBuilder->SetInsertPoint(prevBlock);
  14852. if (!constValue)
  14853. {
  14854. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  14855. // all-const args
  14856. if (wasAllConst)
  14857. {
  14858. methodInst->mMayBeConst = false;
  14859. }
  14860. }
  14861. return constValue;
  14862. }
  14863. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  14864. {
  14865. // Any errors should only be shown in the actual CTOR call
  14866. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  14867. auto methodDef = mCurMethodInstance->mMethodDef;
  14868. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  14869. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  14870. BfCustomAttributes* customAttributes = NULL;
  14871. defer(delete customAttributes);
  14872. BfInvocationExpression* ctorInvocation = NULL;
  14873. if (ctorDeclaration != NULL)
  14874. {
  14875. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  14876. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  14877. {
  14878. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  14879. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  14880. }
  14881. }
  14882. BfTypeInstance* targetType = NULL;
  14883. if (ctorInvocation != NULL)
  14884. {
  14885. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  14886. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  14887. }
  14888. else
  14889. targetType = mCurTypeInstance->mBaseType;
  14890. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  14891. return NULL;
  14892. auto targetRefNode = methodDef->GetRefNode();
  14893. BfType* targetThisType = targetType;
  14894. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  14895. BfExprEvaluator exprEvaluator(this);
  14896. BfResolvedArgs argValues;
  14897. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  14898. {
  14899. argValues.Init(&ctorInvocation->mArguments);
  14900. }
  14901. //
  14902. {
  14903. }
  14904. BfFunctionBindResult bindResult;
  14905. bindResult.mSkipThis = true;
  14906. bindResult.mWantsArgs = true;
  14907. {
  14908. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14909. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14910. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14911. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), true);
  14912. }
  14913. if (bindResult.mMethodInstance == NULL)
  14914. {
  14915. AssertErrorState();
  14916. return BfTypedValue();
  14917. }
  14918. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  14919. {
  14920. return BfTypedValue();
  14921. }
  14922. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14923. bindResult.mIRArgs.RemoveAt(0);
  14924. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  14925. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs, true);
  14926. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  14927. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  14928. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  14929. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  14930. if (appendSizeTypedValue)
  14931. return appendSizeTypedValue;
  14932. if (constOnly)
  14933. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  14934. bool needsRecalc = false;
  14935. for (auto irArg : bindResult.mIRArgs)
  14936. {
  14937. if (irArg.IsFake())
  14938. needsRecalc = true;
  14939. }
  14940. auto calcAppendArgs = bindResult.mIRArgs;
  14941. if (needsRecalc)
  14942. {
  14943. // Do it again, but without mIgnoreWrites set
  14944. BfResolvedArgs argValues;
  14945. argValues.Init(&ctorInvocation->mArguments);
  14946. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14947. BfFunctionBindResult bindResult;
  14948. bindResult.mSkipThis = true;
  14949. bindResult.mWantsArgs = true;
  14950. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14951. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), true);
  14952. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14953. bindResult.mIRArgs.RemoveAt(0);
  14954. calcAppendArgs = bindResult.mIRArgs;
  14955. }
  14956. if (mBfIRBuilder->mIgnoreWrites)
  14957. {
  14958. appendSizeTypedValue = GetFakeTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  14959. }
  14960. else
  14961. {
  14962. BF_ASSERT(calcAppendMethodModule.mFunc);
  14963. appendSizeTypedValue = exprEvaluator.CreateCall(NULL, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  14964. }
  14965. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  14966. return appendSizeTypedValue;
  14967. }
  14968. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  14969. void BfModule::EmitCtorCalcAppend()
  14970. {
  14971. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  14972. return;
  14973. auto methodDef = mCurMethodInstance->mMethodDef;
  14974. auto methodDecl = methodDef->GetMethodDeclaration();
  14975. Array<BfAstNode*> deferredNodeList;
  14976. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14977. if (methodDeclBlock == NULL)
  14978. return;
  14979. AppendAllocVisitor appendAllocVisitor;
  14980. auto baseCalcAppend = CallBaseCtorCalc(false);
  14981. if (baseCalcAppend)
  14982. {
  14983. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  14984. }
  14985. appendAllocVisitor.mModule = this;
  14986. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14987. }
  14988. void BfModule::CreateStaticCtor()
  14989. {
  14990. auto typeDef = mCurTypeInstance->mTypeDef;
  14991. auto methodDef = mCurMethodInstance->mMethodDef;
  14992. BfIRBlock exitBB;
  14993. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  14994. {
  14995. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  14996. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  14997. mBfIRBuilder->MapType(boolType),
  14998. false,
  14999. BfIRLinkageType_Internal,
  15000. GetDefaultValue(boolType),
  15001. "didStaticInit");
  15002. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  15003. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15004. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  15005. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  15006. mBfIRBuilder->SetInsertPoint(initBB);
  15007. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  15008. }
  15009. // Do DLL imports
  15010. if (!mDllImportEntries.empty())
  15011. {
  15012. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  15013. PopulateType(internalType);
  15014. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  15015. if (!getSharedProcAddressInstance)
  15016. {
  15017. if (!mCompiler->mPassInstance->HasFailed())
  15018. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  15019. }
  15020. }
  15021. // Fill in initializer values
  15022. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15023. {
  15024. for (auto fieldDef : typeDef->mFields)
  15025. {
  15026. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic))
  15027. {
  15028. // For extensions, only handle these fields in the appropriate extension
  15029. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15030. continue;
  15031. auto initializer = fieldDef->GetInitializer();
  15032. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15033. if (!fieldInst->mFieldIncluded)
  15034. continue;
  15035. if (fieldInst->mResolvedType->IsVar())
  15036. {
  15037. continue;
  15038. }
  15039. if (fieldInst->IsAppendedObject())
  15040. {
  15041. AppendedObjectInit(fieldInst);
  15042. }
  15043. else if (initializer != NULL)
  15044. {
  15045. UpdateSrcPos(initializer);
  15046. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  15047. }
  15048. }
  15049. }
  15050. auto _CheckInitBlock = [&](BfAstNode* node)
  15051. {
  15052. };
  15053. EmitInitBlocks(_CheckInitBlock);
  15054. }
  15055. else
  15056. {
  15057. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15058. {
  15059. if (tempTypeDef->mFullName == typeDef->mFullName)
  15060. {
  15061. for (auto fieldDef : tempTypeDef->mFields)
  15062. {
  15063. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  15064. {
  15065. if (fieldDef->GetInitializer() != NULL)
  15066. {
  15067. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDef->GetInitializer()))
  15068. {
  15069. sourceClassifier->SetElementType(fieldDef->GetInitializer(), BfSourceElementType_Normal);
  15070. sourceClassifier->VisitChildNoRef(fieldDef->GetInitializer());
  15071. }
  15072. BfType* wantType = NULL;
  15073. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  15074. {
  15075. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  15076. }
  15077. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  15078. if (fieldDef->mIsAppend)
  15079. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  15080. CreateValueFromExpression(fieldDef->GetInitializer(), wantType, exprFlags);
  15081. }
  15082. }
  15083. }
  15084. }
  15085. }
  15086. }
  15087. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15088. CallChainedMethods(mCurMethodInstance, false);
  15089. }
  15090. void BfModule::EmitDtorBody()
  15091. {
  15092. if (!mCurMethodState->mIRExitBlock)
  15093. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15094. if (mCurTypeInstance->IsClosure())
  15095. {
  15096. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  15097. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  15098. auto thisVal = GetThis();
  15099. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  15100. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  15101. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  15102. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  15103. SizedArray<BfIRValue, 1> args;
  15104. args.push_back(thisVal.mValue);
  15105. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  15106. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15107. // Fall through to Object::~this call
  15108. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  15109. if (mIsComptimeModule)
  15110. mCompiler->mCeMachine->QueueMethod(dtorFunc.mMethodInstance, dtorFunc.mFunc);
  15111. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  15112. SizedArray<BfIRValue, 1> vals = { basePtr };
  15113. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  15114. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  15115. mBfIRBuilder->SetTailCall(result);
  15116. return;
  15117. }
  15118. auto typeDef = mCurTypeInstance->mTypeDef;
  15119. auto methodDef = mCurMethodInstance->mMethodDef;
  15120. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15121. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15122. CallChainedMethods(mCurMethodInstance, true);
  15123. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15124. {
  15125. VisitEmbeddedStatement(bodyBlock);
  15126. if (bodyBlock->mCloseBrace != NULL)
  15127. {
  15128. UpdateSrcPos(bodyBlock->mCloseBrace);
  15129. }
  15130. }
  15131. else
  15132. {
  15133. if (methodDeclaration != NULL)
  15134. UpdateSrcPos(methodDeclaration);
  15135. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15136. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  15137. else if (typeDef->mTypeDeclaration != NULL)
  15138. UpdateSrcPos(typeDef->mTypeDeclaration);
  15139. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  15140. {
  15141. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  15142. }
  15143. }
  15144. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15145. {
  15146. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  15147. {
  15148. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  15149. auto fieldDef = fieldInst->GetFieldDef();
  15150. BfFieldDeclaration* fieldDecl = NULL;
  15151. if (fieldDef != NULL)
  15152. fieldDecl = fieldDef->GetFieldDeclaration();
  15153. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDecl != NULL) && (fieldDecl->mFieldDtor != NULL))
  15154. {
  15155. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15156. {
  15157. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15158. continue;
  15159. }
  15160. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  15161. {
  15162. Fail("Structs cannot have field destructors", fieldDecl->mFieldDtor->mTildeToken, true);
  15163. }
  15164. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  15165. auto fieldDtor = fieldDecl->mFieldDtor;
  15166. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  15167. continue;
  15168. UpdateSrcPos(fieldDtor);
  15169. BfScopeData scopeData;
  15170. mCurMethodState->AddScope(&scopeData);
  15171. NewScopeState();
  15172. UpdateSrcPos(fieldDtor);
  15173. bool hasDbgInfo = (!fieldDef->mIsConst);
  15174. if (hasDbgInfo)
  15175. {
  15176. mBfIRBuilder->SaveDebugLocation();
  15177. mBfIRBuilder->ClearDebugLocation();
  15178. }
  15179. BfIRValue value;
  15180. if (fieldDef->mIsStatic)
  15181. {
  15182. value = ReferenceStaticField(fieldInst).mValue;
  15183. }
  15184. else
  15185. {
  15186. PopulateType(fieldInst->mResolvedType);
  15187. if (fieldInst->mResolvedType->IsValuelessType())
  15188. {
  15189. value = mBfIRBuilder->GetFakeVal();
  15190. }
  15191. else if (!mCurTypeInstance->IsValueType())
  15192. {
  15193. auto thisValue = GetThis();
  15194. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  15195. }
  15196. else
  15197. {
  15198. AssertErrorState();
  15199. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15200. }
  15201. }
  15202. BfIRValue staticVal;
  15203. if (hasDbgInfo)
  15204. {
  15205. BfIRValue dbgShowValue = value;
  15206. BfLocalVariable* localDef = new BfLocalVariable();
  15207. localDef->mName = "_";
  15208. localDef->mResolvedType = fieldInst->mResolvedType;
  15209. if (fieldInst->IsAppendedObject())
  15210. {
  15211. localDef->mValue = mBfIRBuilder->CreateBitCast(value, mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15212. }
  15213. else
  15214. {
  15215. localDef->mAddr = value;
  15216. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  15217. {
  15218. // Create another pointer indirection, a ref to the gep
  15219. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  15220. auto allocaInst = CreateAlloca(refFieldType);
  15221. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  15222. localDef->mResolvedType = refFieldType;
  15223. localDef->mAddr = allocaInst;
  15224. }
  15225. }
  15226. mBfIRBuilder->RestoreDebugLocation();
  15227. auto defLocalVar = AddLocalVariableDef(localDef, true);
  15228. if (!fieldInst->IsAppendedObject())
  15229. {
  15230. // Put back so we actually modify the correct value*/
  15231. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  15232. defLocalVar->mAddr = value;
  15233. }
  15234. }
  15235. while (fieldDtor != NULL)
  15236. {
  15237. if (mCompiler->mResolvePassData != NULL)
  15238. {
  15239. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15240. {
  15241. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15242. sourceClassifier->VisitChild(fieldDtor);
  15243. }
  15244. }
  15245. UpdateSrcPos(fieldDtor);
  15246. VisitEmbeddedStatement(fieldDtor->mBody);
  15247. fieldDtor = fieldDtor->mNextFieldDtor;
  15248. }
  15249. RestoreScopeState();
  15250. }
  15251. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldInst->IsAppendedObject()))
  15252. {
  15253. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15254. {
  15255. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15256. continue;
  15257. }
  15258. auto refNode = fieldDef->GetRefNode();
  15259. UpdateSrcPos(refNode);
  15260. auto objectType = mContext->mBfObjectType;
  15261. BfTypeInstance* checkTypeInst = mCurTypeInstance->ToTypeInstance();
  15262. BfTypedValue val;
  15263. if (fieldDef->mIsStatic)
  15264. val = ReferenceStaticField(fieldInst);
  15265. else
  15266. {
  15267. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  15268. val = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  15269. }
  15270. bool allowPrivate = checkTypeInst == mCurTypeInstance;
  15271. bool allowProtected = allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst);
  15272. while (checkTypeInst != NULL)
  15273. {
  15274. auto dtorMethodDef = checkTypeInst->mTypeDef->GetMethodByName("~this");
  15275. if (dtorMethodDef)
  15276. {
  15277. if (!CheckProtection(dtorMethodDef->mProtection, checkTypeInst->mTypeDef, allowProtected, allowPrivate))
  15278. {
  15279. auto error = Fail(StrFormat("'%s.~this()' is inaccessible due to its protection level", TypeToString(checkTypeInst).c_str()), refNode); // CS0122
  15280. }
  15281. }
  15282. checkTypeInst = checkTypeInst->mBaseType;
  15283. allowPrivate = false;
  15284. }
  15285. // call dtor
  15286. BfExprEvaluator expressionEvaluator(this);
  15287. PopulateType(val.mType);
  15288. PopulateType(objectType, BfPopulateType_DataAndMethods);
  15289. if (objectType->mVirtualMethodTable.size() == 0)
  15290. {
  15291. if (!mCompiler->IsAutocomplete())
  15292. AssertErrorState();
  15293. }
  15294. else if (!IsSkippingExtraResolveChecks())
  15295. {
  15296. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  15297. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  15298. SizedArray<BfIRValue, 4> llvmArgs;
  15299. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  15300. expressionEvaluator.CreateCall(refNode, methodInstance, mBfIRBuilder->GetFakeVal(), false, llvmArgs);
  15301. }
  15302. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  15303. {
  15304. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  15305. auto int8PtrVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(int8PtrType));
  15306. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  15307. }
  15308. }
  15309. }
  15310. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15311. {
  15312. auto checkBaseType = mCurTypeInstance->mBaseType;
  15313. while (checkBaseType != NULL)
  15314. {
  15315. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15316. {
  15317. if (bodyBlock->mCloseBrace != NULL)
  15318. UpdateSrcPos(bodyBlock->mCloseBrace);
  15319. }
  15320. else
  15321. {
  15322. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  15323. }
  15324. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  15325. if (dtorMethodDef != NULL)
  15326. {
  15327. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  15328. if (IsSkippingExtraResolveChecks())
  15329. {
  15330. // Nothing
  15331. }
  15332. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  15333. {
  15334. if ((!IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  15335. {
  15336. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  15337. SizedArray<BfIRValue, 1> vals = { basePtr };
  15338. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  15339. if (mIsComptimeModule)
  15340. mCompiler->mCeMachine->QueueMethod(dtorMethodInstance.mMethodInstance, dtorMethodInstance.mFunc);
  15341. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  15342. }
  15343. }
  15344. else
  15345. {
  15346. // Invalid base dtor declaration
  15347. AssertErrorState();
  15348. }
  15349. break;
  15350. }
  15351. checkBaseType = checkBaseType->mBaseType;
  15352. }
  15353. }
  15354. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15355. }
  15356. else
  15357. {
  15358. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15359. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15360. // resolve pass, NOT the autocomplete expression
  15361. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15362. {
  15363. if (tempTypeDef->mFullName == typeDef->mFullName)
  15364. {
  15365. for (auto fieldDef : tempTypeDef->mFields)
  15366. {
  15367. auto fieldDecl = fieldDef->GetFieldDeclaration();
  15368. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  15369. (fieldDecl->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  15370. {
  15371. BfType* fieldType = NULL;
  15372. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  15373. {
  15374. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  15375. auto curFieldDef = curFieldInstance->GetFieldDef();
  15376. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  15377. fieldType = curFieldInstance->GetResolvedType();
  15378. }
  15379. if (fieldType == NULL)
  15380. fieldType = GetPrimitiveType(BfTypeCode_Var);
  15381. auto fieldDtor = fieldDecl->mFieldDtor;
  15382. BfScopeData scopeData;
  15383. mCurMethodState->AddScope(&scopeData);
  15384. NewScopeState();
  15385. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  15386. if (fieldType != NULL)
  15387. {
  15388. BfLocalVariable* localDef = new BfLocalVariable();
  15389. localDef->mName = "_";
  15390. localDef->mResolvedType = fieldType;
  15391. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  15392. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15393. AddLocalVariableDef(localDef);
  15394. }
  15395. while (fieldDtor != NULL)
  15396. {
  15397. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15398. {
  15399. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15400. sourceClassifier->VisitChild(fieldDtor);
  15401. }
  15402. UpdateSrcPos(fieldDtor);
  15403. VisitEmbeddedStatement(fieldDtor->mBody);
  15404. fieldDtor = fieldDtor->mNextFieldDtor;
  15405. }
  15406. RestoreScopeState();
  15407. }
  15408. }
  15409. }
  15410. }
  15411. }
  15412. }
  15413. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  15414. {
  15415. BF_ASSERT(methodInstance->mIsReified);
  15416. auto typeInstance = methodInstance->GetOwner();
  15417. bool foundDllImportAttr = false;
  15418. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  15419. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  15420. {
  15421. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  15422. {
  15423. foundDllImportAttr = true;
  15424. }
  15425. }
  15426. if (!foundDllImportAttr)
  15427. {
  15428. AssertErrorState();
  15429. return BfIRValue();
  15430. }
  15431. StringT<512> name = "bf_hs_preserve@";
  15432. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  15433. name += "__imp";
  15434. BfIRType returnType;
  15435. SizedArray<BfIRType, 8> paramTypes;
  15436. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  15437. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  15438. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  15439. BfIRValue initVal;
  15440. if (define)
  15441. {
  15442. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  15443. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  15444. }
  15445. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  15446. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  15447. {
  15448. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15449. auto ptrType = CreatePointerType(voidType);
  15450. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  15451. }
  15452. return globalVar;
  15453. }
  15454. void BfModule::CreateDllImportMethod()
  15455. {
  15456. if (mBfIRBuilder->mIgnoreWrites)
  15457. return;
  15458. auto globalVar = mFuncReferences[mCurMethodInstance];
  15459. if (!globalVar)
  15460. return;
  15461. bool allowTailCall = true;
  15462. mBfIRBuilder->ClearDebugLocation();
  15463. bool isHotCompile = mCompiler->IsHotCompile();
  15464. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  15465. if (isHotCompile)
  15466. {
  15467. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  15468. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  15469. }
  15470. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  15471. BfIRType returnType;
  15472. SizedArray<BfIRType, 8> paramTypes;
  15473. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15474. SizedArray<BfIRValue, 8> args;
  15475. for (int i = 0; i < (int)paramTypes.size(); i++)
  15476. args.push_back(mBfIRBuilder->GetArgument(i));
  15477. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15478. if (isHotCompile)
  15479. {
  15480. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  15481. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  15482. if (callingConvention == BfIRCallingConv_StdCall)
  15483. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  15484. else if (callingConvention == BfIRCallingConv_FastCall)
  15485. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  15486. else
  15487. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15488. if (allowTailCall)
  15489. mBfIRBuilder->SetTailCall(result);
  15490. CreateReturn(result);
  15491. mCurMethodState->mHadReturn = true;
  15492. }
  15493. if (HasCompiledOutput())
  15494. {
  15495. BfDllImportEntry dllImportEntry;
  15496. dllImportEntry.mFuncVar = globalVar;
  15497. dllImportEntry.mMethodInstance = mCurMethodInstance;
  15498. mDllImportEntries.push_back(dllImportEntry);
  15499. }
  15500. }
  15501. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  15502. {
  15503. auto methodDef = methodInstance->mMethodDef;
  15504. BfTypeInstance* owner = NULL;
  15505. if (!methodDef->mIsStatic)
  15506. owner = methodInstance->GetThisType()->ToTypeInstance();
  15507. if (owner == NULL)
  15508. owner = methodInstance->GetOwner();
  15509. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  15510. return BfIRCallingConv_CDecl;
  15511. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  15512. return BfIRCallingConv_StdCall;
  15513. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  15514. return BfIRCallingConv_FastCall;
  15515. if (!methodDef->mIsStatic)
  15516. {
  15517. if (owner->mIsCRepr)
  15518. return BfIRCallingConv_ThisCall;
  15519. if ((!owner->IsValuelessType()) &&
  15520. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  15521. return BfIRCallingConv_ThisCall;
  15522. }
  15523. return BfIRCallingConv_CDecl;
  15524. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  15525. }
  15526. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  15527. {
  15528. BfMethodDef* methodDef = NULL;
  15529. if (methodInstance != NULL)
  15530. methodDef = methodInstance->mMethodDef;
  15531. if (!func)
  15532. return;
  15533. if (mCompiler->mOptions.mNoFramePointerElim)
  15534. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  15535. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  15536. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  15537. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  15538. if (methodInstance == NULL)
  15539. return;
  15540. if (methodInstance->mReturnType->IsVar())
  15541. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_VarRet);
  15542. if (methodDef->mImportKind == BfImportKind_Export)
  15543. {
  15544. if (methodDef->mDeclaringType->mProject->mTargetType != BfTargetType_BeefLib_StaticLib)
  15545. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  15546. }
  15547. if (methodDef->mIsNoReturn)
  15548. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  15549. auto callingConv = GetIRCallingConvention(methodInstance);
  15550. if (callingConv != BfIRCallingConv_CDecl)
  15551. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  15552. if (isInlined)
  15553. {
  15554. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15555. }
  15556. int argIdx = 0;
  15557. int paramIdx = 0;
  15558. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  15559. paramIdx = -1;
  15560. int argCount = methodInstance->GetIRFunctionParamCount(this);
  15561. while (argIdx < argCount)
  15562. {
  15563. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  15564. {
  15565. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  15566. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  15567. argIdx++;
  15568. continue;
  15569. }
  15570. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  15571. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  15572. paramIdx++;
  15573. BfType* resolvedTypeRef = NULL;
  15574. BfType* resolvedTypeRef2 = NULL;
  15575. String paramName;
  15576. bool isSplattable = false;
  15577. bool tryLowering = !mIsComptimeModule;
  15578. if (isThis)
  15579. {
  15580. paramName = "this";
  15581. if (methodInstance->mIsClosure)
  15582. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  15583. else
  15584. resolvedTypeRef = methodInstance->GetThisType();
  15585. isSplattable = (!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(-1));
  15586. tryLowering = (!mIsComptimeModule) && (methodInstance->AllowsSplatting(-1));
  15587. }
  15588. else
  15589. {
  15590. paramName = methodInstance->GetParamName(paramIdx);
  15591. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  15592. if (resolvedTypeRef->IsMethodRef())
  15593. isSplattable = true;
  15594. else if ((!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(paramIdx)))
  15595. {
  15596. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15597. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15598. {
  15599. // crepr splat is always splattable
  15600. isSplattable = true;
  15601. }
  15602. else
  15603. {
  15604. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15605. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15606. isSplattable = true;
  15607. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  15608. isSplattable = true;
  15609. }
  15610. }
  15611. }
  15612. if (tryLowering)
  15613. {
  15614. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15615. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15616. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  15617. {
  15618. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  15619. argIdx++;
  15620. if (loweredTypeCode2 != BfTypeCode_None)
  15621. {
  15622. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  15623. argIdx++;
  15624. }
  15625. paramIdx++;
  15626. continue;
  15627. }
  15628. }
  15629. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  15630. {
  15631. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  15632. int addDeref = -1;
  15633. if (resolvedTypeRef->IsRef())
  15634. {
  15635. auto refType = (BfRefType*)resolvedTypeRef;
  15636. auto elementType = refType->mElementType;
  15637. PopulateType(elementType, BfPopulateType_Data);
  15638. addDeref = elementType->mSize;
  15639. if ((addDeref <= 0) && (!elementType->IsValuelessType()) && (!elementType->IsOpaque()))
  15640. AssertErrorState();
  15641. }
  15642. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  15643. {
  15644. if (isThis)
  15645. {
  15646. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  15647. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  15648. addDeref = resolvedTypeRef->mSize;
  15649. }
  15650. else if (methodInstance->WantsStructsAttribByVal(resolvedTypeRef))
  15651. {
  15652. mBfIRBuilder->PopulateType(resolvedTypeRef, BfIRPopulateType_Full);
  15653. BF_ASSERT(resolvedTypeRef->mAlign > 0);
  15654. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  15655. }
  15656. }
  15657. else if (resolvedTypeRef->IsPrimitiveType())
  15658. {
  15659. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  15660. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  15661. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  15662. }
  15663. if (addDeref >= 0)
  15664. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  15665. argIdx++;
  15666. };
  15667. if (isSplattable)
  15668. {
  15669. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  15670. {
  15671. if (checkType->IsStruct())
  15672. {
  15673. auto checkTypeInstance = checkType->ToTypeInstance();
  15674. if (checkTypeInstance->mBaseType != NULL)
  15675. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  15676. if (checkTypeInstance->mIsUnion)
  15677. {
  15678. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  15679. checkTypeLambda(unionInnerType, curName + "_data");
  15680. }
  15681. else
  15682. {
  15683. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  15684. {
  15685. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  15686. auto fieldDef = fieldInstance->GetFieldDef();
  15687. if (fieldInstance->mDataIdx >= 0)
  15688. {
  15689. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  15690. }
  15691. }
  15692. }
  15693. if (checkTypeInstance->IsEnum())
  15694. {
  15695. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  15696. argIdx++;
  15697. }
  15698. }
  15699. else if (checkType->IsMethodRef())
  15700. {
  15701. auto methodRefType = (BfMethodRefType*)checkType;
  15702. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  15703. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  15704. {
  15705. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  15706. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  15707. {
  15708. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  15709. }
  15710. else
  15711. {
  15712. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  15713. }
  15714. }
  15715. }
  15716. else if (!checkType->IsValuelessType())
  15717. {
  15718. _SetupParam(curName, checkType);
  15719. }
  15720. };
  15721. checkTypeLambda(resolvedTypeRef, paramName);
  15722. paramIdx++;
  15723. continue;
  15724. }
  15725. _SetupParam(paramName, resolvedTypeRef);
  15726. if (resolvedTypeRef2 != NULL)
  15727. _SetupParam(paramName, resolvedTypeRef2);
  15728. paramIdx++;
  15729. }
  15730. }
  15731. void BfModule::EmitInitBlocks(const std::function<void(BfAstNode*)>& initBlockCallback)
  15732. {
  15733. auto methodDef = mCurMethodInstance->mMethodDef;
  15734. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  15735. BfMemberSetEntry* entry = NULL;
  15736. BfMethodDef* initMethodDef = NULL;
  15737. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  15738. if (entry != NULL)
  15739. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  15740. SizedArray<BfAstNode*, 8> initBodies;
  15741. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  15742. {
  15743. if (initMethodDef->mDeclaringType->GetDefinition() != methodDef->mDeclaringType->GetDefinition())
  15744. continue;
  15745. if (initMethodDef->mMethodType != BfMethodType_Init)
  15746. continue;
  15747. if (initMethodDef->mIsStatic != methodDef->mIsStatic)
  15748. continue;
  15749. initBodies.Insert(0, initMethodDef->mBody);
  15750. }
  15751. for (auto body : initBodies)
  15752. {
  15753. initBlockCallback(body);
  15754. VisitEmbeddedStatement(body);
  15755. }
  15756. }
  15757. void BfModule::EmitCtorBody(bool& skipBody)
  15758. {
  15759. auto methodInstance = mCurMethodInstance;
  15760. auto methodDef = methodInstance->mMethodDef;
  15761. auto methodDeclaration = methodDef->mMethodDeclaration;
  15762. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  15763. auto typeDef = mCurTypeInstance->mTypeDef;
  15764. BfCustomAttributes* customAttributes = NULL;
  15765. defer(delete customAttributes);
  15766. BfInvocationExpression* ctorInvocation = NULL;
  15767. BfAttributeState attributeState;
  15768. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  15769. if (ctorDeclaration != NULL)
  15770. {
  15771. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  15772. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  15773. {
  15774. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  15775. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  15776. }
  15777. }
  15778. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  15779. // Prologue
  15780. mBfIRBuilder->ClearDebugLocation();
  15781. bool hadThisInitializer = false;
  15782. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15783. {
  15784. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15785. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15786. if (targetToken->GetToken() == BfToken_This)
  15787. {
  15788. hadThisInitializer = true;
  15789. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  15790. mCurMethodState->LocalDefined(GetThisVariable());
  15791. }
  15792. }
  15793. // Zero out memory for default ctor
  15794. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()) && (methodInstance->mChainType != BfMethodChainType_ChainMember) &&
  15795. (!mCurMethodState->mLocals.IsEmpty()))
  15796. {
  15797. if (mCurTypeInstance->IsTypedPrimitive())
  15798. {
  15799. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15800. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  15801. }
  15802. else if (mCurTypeInstance->mInstSize > 0)
  15803. {
  15804. BfIRValue fillValue = GetConstValue8(0);
  15805. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  15806. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15807. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  15808. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  15809. }
  15810. }
  15811. BfAstNode* baseCtorNode = NULL;
  15812. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  15813. baseCtorNode = ctorInvocation->mTarget;
  15814. else if (methodDef->mBody != NULL)
  15815. baseCtorNode = methodDef->mBody;
  15816. else if (ctorDeclaration != NULL)
  15817. baseCtorNode = ctorDeclaration;
  15818. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15819. baseCtorNode = methodDef->mDeclaringType->GetRefNode();
  15820. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15821. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  15822. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  15823. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  15824. else
  15825. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  15826. bool calledCtorNoBody = false;
  15827. if ((mCurTypeInstance->IsTypedPrimitive()) && (!mCurTypeInstance->IsValuelessType()))
  15828. {
  15829. // Zero out typed primitives in ctor
  15830. mBfIRBuilder->CreateAlignedStore(GetDefaultValue(mCurTypeInstance->GetUnderlyingType()), mBfIRBuilder->GetArgument(0), mCurTypeInstance->mAlign);
  15831. }
  15832. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  15833. {
  15834. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  15835. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  15836. {
  15837. BfMethodDef* defaultCtor = NULL;
  15838. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  15839. {
  15840. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  15841. {
  15842. defaultCtor = methodDef;
  15843. }
  15844. }
  15845. if (defaultCtor != NULL)
  15846. {
  15847. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  15848. SetIllegalSrcPos();
  15849. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  15850. BfExprEvaluator exprEvaluator(this);
  15851. SizedArray<BfIRValue, 1> irArgs;
  15852. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  15853. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  15854. if (mIsComptimeModule)
  15855. mCompiler->mCeMachine->QueueMethod(moduleMethodInstance);
  15856. calledCtorNoBody = true;
  15857. }
  15858. }
  15859. }
  15860. // Initialize fields (if applicable)
  15861. if (mCurTypeInstance->IsBoxed())
  15862. {
  15863. skipBody = true;
  15864. }
  15865. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  15866. {
  15867. // Field initializers occur in CtorNoBody methods for extensions
  15868. }
  15869. else if (!hadThisInitializer)
  15870. {
  15871. // If we had a 'this' initializer, that other ctor will have initialized our fields
  15872. //auto
  15873. if ((!mCompiler->mIsResolveOnly) ||
  15874. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  15875. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  15876. {
  15877. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  15878. // to properly set the assigned flags
  15879. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  15880. bool hadInlineInitBlock = false;
  15881. BfScopeData scopeData;
  15882. scopeData.mInInitBlock = true;
  15883. auto _CheckInitBlock = [&](BfAstNode* node)
  15884. {
  15885. if (!hadInlineInitBlock)
  15886. {
  15887. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  15888. {
  15889. UpdateSrcPos(baseCtorNode);
  15890. if (methodDef->mBody == NULL)
  15891. SetIllegalSrcPos();
  15892. // 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
  15893. EmitEnsureInstructionAt();
  15894. BfType* thisType = mCurTypeInstance;
  15895. if (thisType->IsValueType())
  15896. thisType = CreateRefType(thisType);
  15897. SizedArray<BfIRMDNode, 1> diParamTypes;
  15898. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  15899. mCurMethodState->AddScope(&scopeData);
  15900. NewScopeState();
  15901. int flags = 0;
  15902. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  15903. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  15904. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  15905. String linkageName;
  15906. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mCurBuilder != NULL))
  15907. linkageName = StrFormat("%d", mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(mCurMethodInstance, "$initFields"));
  15908. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", linkageName, mCurFilePosition.mFileInstance->mDIFile,
  15909. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  15910. UpdateSrcPos(node);
  15911. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  15912. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  15913. //
  15914. {
  15915. auto loadedThis = GetThis();
  15916. // LLVM can't handle two variables pointing to the same value
  15917. BfIRValue copiedThisPtr;
  15918. copiedThisPtr = CreateAlloca(thisType);
  15919. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  15920. mBfIRBuilder->ClearDebugLocation(storeInst);
  15921. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  15922. }
  15923. hadInlineInitBlock = true;
  15924. }
  15925. else
  15926. {
  15927. // Just do a simple one
  15928. mCurMethodState->AddScope(&scopeData);
  15929. NewScopeState();
  15930. hadInlineInitBlock = true;
  15931. }
  15932. }
  15933. UpdateSrcPos(node);
  15934. };
  15935. for (auto fieldDef : typeDef->mFields)
  15936. {
  15937. // For extensions, only handle these fields in the appropriate extension
  15938. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15939. continue;
  15940. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  15941. {
  15942. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15943. if (!fieldInst->mFieldIncluded)
  15944. continue;
  15945. if (fieldInst->mDataIdx < 0)
  15946. continue;
  15947. auto initializer = fieldDef->GetInitializer();
  15948. if (fieldInst->IsAppendedObject())
  15949. {
  15950. UpdateSrcPos(fieldDef->GetNameNode());
  15951. AppendedObjectInit(fieldInst);
  15952. continue;
  15953. }
  15954. if (initializer == NULL)
  15955. {
  15956. continue;
  15957. // if (fieldDef->mProtection != BfProtection_Hidden)
  15958. // continue;
  15959. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  15960. // continue;
  15961. }
  15962. if (fieldInst->mResolvedType == NULL)
  15963. {
  15964. BF_ASSERT(mHadBuildError);
  15965. continue;
  15966. }
  15967. if (initializer != NULL)
  15968. {
  15969. _CheckInitBlock(initializer);
  15970. }
  15971. BfIRValue fieldAddr;
  15972. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  15973. {
  15974. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  15975. }
  15976. else
  15977. {
  15978. // Failed
  15979. }
  15980. auto assignValue = GetFieldInitializerValue(fieldInst);
  15981. if (mCurTypeInstance->IsUnion())
  15982. {
  15983. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  15984. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  15985. }
  15986. if ((fieldAddr) && (assignValue))
  15987. mBfIRBuilder->CreateAlignedStore(assignValue.mValue, fieldAddr, fieldInst->mResolvedType->mAlign);
  15988. }
  15989. }
  15990. EmitInitBlocks(_CheckInitBlock);
  15991. if (hadInlineInitBlock)
  15992. {
  15993. RestoreScopeState();
  15994. // This gets set to false because of AddScope but we actually are still in the head block
  15995. mCurMethodState->mInHeadScope = true;
  15996. // Make sure we emit a return even if we had a NoReturn call or return inside ourselves
  15997. mCurMethodState->mHadReturn = false;
  15998. mCurMethodState->mLeftBlockUncond = false;
  15999. }
  16000. }
  16001. else // Autocomplete case
  16002. {
  16003. BfScopeData scopeData;
  16004. scopeData.mInInitBlock = true;
  16005. mCurMethodState->AddScope(&scopeData);
  16006. NewScopeState();
  16007. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  16008. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  16009. // resolve pass, NOT the autocomplete expression
  16010. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  16011. {
  16012. if (tempTypeDef->mFullName == typeDef->mFullName)
  16013. {
  16014. for (auto fieldDef : tempTypeDef->mFields)
  16015. {
  16016. auto initializer = fieldDef->GetInitializer();
  16017. if ((!fieldDef->mIsStatic) && (initializer != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  16018. {
  16019. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  16020. {
  16021. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  16022. sourceClassifier->VisitChild(initializer);
  16023. }
  16024. BfType* wantType = NULL;
  16025. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) &&
  16026. (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  16027. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowInferredSizedArray);
  16028. if ((wantType != NULL) &&
  16029. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  16030. wantType = NULL;
  16031. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  16032. if (fieldDef->mIsAppend)
  16033. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  16034. CreateValueFromExpression(initializer, wantType, exprFlags);
  16035. }
  16036. }
  16037. tempTypeDef->PopulateMemberSets();
  16038. BfMemberSetEntry* entry = NULL;
  16039. BfMethodDef* initMethodDef = NULL;
  16040. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  16041. if (entry != NULL)
  16042. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  16043. SizedArray<BfAstNode*, 8> initBodies;
  16044. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  16045. {
  16046. if (initMethodDef->mMethodType != BfMethodType_Init)
  16047. continue;
  16048. initBodies.Insert(0, initMethodDef->mBody);
  16049. }
  16050. for (auto body : initBodies)
  16051. VisitEmbeddedStatement(body);
  16052. }
  16053. }
  16054. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  16055. for (auto fieldDef : typeDef->mFields)
  16056. {
  16057. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->GetInitializer() != NULL))
  16058. {
  16059. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  16060. if (fieldDef->GetInitializer() != NULL)
  16061. MarkFieldInitialized(fieldInst);
  16062. }
  16063. }
  16064. RestoreScopeState();
  16065. }
  16066. }
  16067. if (!methodInstance->mIsAutocompleteMethod)
  16068. {
  16069. if (auto autoDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  16070. {
  16071. BfExprEvaluator exprEvaluator(this);
  16072. for (int paramIdx = 0; paramIdx < methodDef->mParams.mSize; paramIdx++)
  16073. {
  16074. auto paramDef = methodDef->mParams[paramIdx];
  16075. auto& fieldInstance = mCurTypeInstance->mFieldInstances[paramIdx];
  16076. BF_ASSERT(paramDef->mName == fieldInstance.GetFieldDef()->mName);
  16077. if (fieldInstance.mDataIdx < 0)
  16078. continue;
  16079. if (paramDef->mParamKind != BfParamKind_Normal)
  16080. continue;
  16081. auto localVar = mCurMethodState->mLocals[paramIdx + 1];
  16082. BF_ASSERT(localVar->mName == paramDef->mName);
  16083. auto localVal = exprEvaluator.LoadLocal(localVar);
  16084. localVal = LoadOrAggregateValue(localVal);
  16085. if (!localVal.mType->IsVar())
  16086. {
  16087. auto thisVal = GetThis();
  16088. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance.mDataIdx);
  16089. if (mCurTypeInstance->IsUnion())
  16090. fieldPtr = mBfIRBuilder->CreateBitCast(fieldPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInstance.mResolvedType)));
  16091. mBfIRBuilder->CreateAlignedStore(localVal.mValue, fieldPtr, localVar->mResolvedType->mAlign);
  16092. }
  16093. MarkFieldInitialized(&fieldInstance);
  16094. }
  16095. }
  16096. }
  16097. // Call base ctor (if applicable)
  16098. BfTypeInstance* targetType = NULL;
  16099. BfAstNode* targetRefNode = NULL;
  16100. if (ctorDeclaration != NULL)
  16101. targetRefNode = ctorDeclaration->mInitializer;
  16102. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  16103. targetRefNode = invocationExpr->mTarget;
  16104. if (baseCtorNode != NULL)
  16105. {
  16106. UpdateSrcPos(baseCtorNode);
  16107. if (methodDef->mBody == NULL)
  16108. SetIllegalSrcPos();
  16109. }
  16110. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16111. {
  16112. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  16113. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  16114. }
  16115. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()) && (methodDef->mMethodType != BfMethodType_CtorNoBody))
  16116. {
  16117. auto baseType = mCurTypeInstance->mBaseType;
  16118. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  16119. ((baseType->mTypeDef != mCompiler->mValueTypeTypeDef) || (!mContext->mCanSkipValueTypeCtor)) &&
  16120. ((baseType->mTypeDef != mCompiler->mBfObjectTypeDef) || (!mContext->mCanSkipObjectCtor)))
  16121. {
  16122. // Try to find a ctor without any params first
  16123. BfMethodDef* matchedMethod = NULL;
  16124. bool hadCtorWithAllDefaults = false;
  16125. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  16126. for (int pass = 0; pass < 2; pass++)
  16127. {
  16128. baseType->mTypeDef->PopulateMemberSets();
  16129. BfMemberSetEntry* entry = NULL;
  16130. BfMethodDef* checkMethodDef = NULL;
  16131. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  16132. if (entry != NULL)
  16133. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  16134. while (checkMethodDef != NULL)
  16135. {
  16136. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  16137. if (isHiddenGenerated)
  16138. {
  16139. // Allow calling of the default base ctor if it is implicitly defined
  16140. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  16141. allowMethod = true;
  16142. }
  16143. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  16144. {
  16145. if (checkMethodDef->mParams.size() == 0)
  16146. {
  16147. if (matchedMethod != NULL)
  16148. {
  16149. // Has multiple matched methods - can happen from extensions
  16150. matchedMethod = NULL;
  16151. break;
  16152. }
  16153. matchedMethod = checkMethodDef;
  16154. }
  16155. else if (isHiddenGenerated)
  16156. {
  16157. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  16158. hadCtorWithAllDefaults = true;
  16159. }
  16160. }
  16161. checkMethodDef = checkMethodDef->mNextWithSameName;
  16162. }
  16163. if (matchedMethod != NULL)
  16164. break;
  16165. }
  16166. if ((HasExecutedOutput()) && (matchedMethod != NULL))
  16167. {
  16168. SizedArray<BfIRValue, 1> args;
  16169. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  16170. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  16171. {
  16172. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  16173. args.push_back(basePtr);
  16174. }
  16175. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  16176. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  16177. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  16178. if (callingConv != BfIRCallingConv_CDecl)
  16179. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  16180. if (mIsComptimeModule)
  16181. mCompiler->mCeMachine->QueueMethod(ctorBodyMethodInstance);
  16182. }
  16183. if (matchedMethod == NULL)
  16184. {
  16185. targetType = mCurTypeInstance->mBaseType;
  16186. if (ctorDeclaration != NULL)
  16187. targetRefNode = ctorDeclaration->mThisToken;
  16188. else if (typeDef->mTypeDeclaration != NULL)
  16189. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  16190. }
  16191. }
  16192. }
  16193. if (methodDef->mHasAppend)
  16194. {
  16195. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  16196. }
  16197. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  16198. {
  16199. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  16200. {
  16201. if (targetType == mCurTypeInstance)
  16202. {
  16203. auto thisVariable = GetThisVariable();
  16204. if (thisVariable != NULL)
  16205. {
  16206. thisVariable->mUnassignedFieldFlags = 0;
  16207. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16208. }
  16209. }
  16210. targetType = NULL;
  16211. }
  16212. }
  16213. auto autoComplete = mCompiler->GetAutoComplete();
  16214. if (targetType != NULL)
  16215. {
  16216. BfAstNode* refNode = methodDeclaration;
  16217. if (refNode == NULL)
  16218. refNode = typeDef->mTypeDeclaration;
  16219. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  16220. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  16221. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16222. {
  16223. auto invocationExpr = ctorInvocation;
  16224. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  16225. }
  16226. BfType* targetThisType = targetType;
  16227. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  16228. BfExprEvaluator exprEvaluator(this);
  16229. BfResolvedArgs argValues;
  16230. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16231. {
  16232. argValues.Init(&ctorInvocation->mArguments);
  16233. if (gDebugStuff)
  16234. {
  16235. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  16236. }
  16237. }
  16238. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  16239. BfTypedValue appendIdxVal;
  16240. if (methodDef->mHasAppend)
  16241. {
  16242. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  16243. BF_ASSERT(localVar->mName == "appendIdx");
  16244. auto intRefType = localVar->mResolvedType;
  16245. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  16246. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  16247. }
  16248. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), methodDef->mHasAppend, &appendIdxVal);
  16249. if (autoComplete != NULL)
  16250. {
  16251. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  16252. {
  16253. if (autoComplete->mMethodMatchInfo != NULL)
  16254. autoComplete->mIsCapturingMethodMatchInfo = true;
  16255. else
  16256. autoComplete->mIsCapturingMethodMatchInfo = false;
  16257. }
  16258. else
  16259. autoComplete->mIsCapturingMethodMatchInfo = false;
  16260. }
  16261. }
  16262. auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration);
  16263. if ((autoComplete != NULL) && (autoComplete->CheckFixit(methodDeclaration)) && (methodDeclaration != NULL) && (autoCtorDecl != NULL))
  16264. {
  16265. auto typeDecl = methodDef->mDeclaringType->mTypeDeclaration;
  16266. BfParserData* parser = typeDecl->GetSourceData()->ToParserData();
  16267. if (parser != NULL)
  16268. {
  16269. String fixitStr = "Expand auto constructor\t";
  16270. int insertPos = typeDecl->mSrcStart;
  16271. bool needsBlock = false;
  16272. if (auto defBlock = BfNodeDynCast<BfBlock>(typeDecl->mDefineNode))
  16273. {
  16274. insertPos = defBlock->mOpenBrace->mSrcStart + 1;
  16275. }
  16276. else if (auto tokenNode = BfNodeDynCast<BfTokenNode>(typeDecl->mDefineNode))
  16277. {
  16278. insertPos = tokenNode->mSrcStart;
  16279. fixitStr += StrFormat("delete|%s-%d|\x01",
  16280. autoComplete->FixitGetLocation(parser, tokenNode->mSrcStart).c_str(), tokenNode->mSrcEnd - tokenNode->mSrcStart);
  16281. needsBlock = true;
  16282. }
  16283. int srcStart = methodDeclaration->mSrcStart;
  16284. if ((autoCtorDecl->mPrefix == NULL) && (typeDecl->mColonToken != NULL))
  16285. srcStart = typeDecl->mColonToken->mSrcStart;
  16286. while ((srcStart > 0) && (::isspace((uint8)parser->mSrc[srcStart - 1])))
  16287. srcStart--;
  16288. fixitStr += StrFormat("expand|%s|%d|",
  16289. parser->mFileName.c_str(), insertPos);
  16290. if (needsBlock)
  16291. fixitStr += "\t";
  16292. else
  16293. fixitStr += "\f";
  16294. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16295. {
  16296. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16297. paramStr.Replace('\n', '\r');
  16298. fixitStr += "public ";
  16299. fixitStr += paramStr;
  16300. fixitStr += ";\r";
  16301. }
  16302. fixitStr += "\rpublic this(";
  16303. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16304. {
  16305. if (paramIdx > 0)
  16306. fixitStr += ", ";
  16307. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16308. paramStr.Replace('\n', '\r');
  16309. fixitStr += paramStr;
  16310. }
  16311. fixitStr += ")\t";
  16312. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16313. {
  16314. if (paramIdx > 0)
  16315. fixitStr += "\r";
  16316. auto nameNode = autoCtorDecl->mParams[paramIdx]->mNameNode;
  16317. if (nameNode == NULL)
  16318. continue;
  16319. String nameStr = nameNode->ToString();
  16320. fixitStr += "this.";
  16321. fixitStr += nameStr;
  16322. fixitStr += " = ";
  16323. fixitStr += nameStr;
  16324. fixitStr += ";";
  16325. }
  16326. fixitStr += "\b";
  16327. if (needsBlock)
  16328. fixitStr += "\b";
  16329. fixitStr += StrFormat("\x01""delete|%s-%d|",
  16330. autoComplete->FixitGetLocation(parser, srcStart).c_str(), autoCtorDecl->mSrcEnd - srcStart);
  16331. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", fixitStr.c_str()));
  16332. }
  16333. }
  16334. }
  16335. void BfModule::EmitEnumToStringBody()
  16336. {
  16337. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16338. auto strVal = CreateAlloca(stringType);
  16339. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  16340. BfExprEvaluator exprEvaluator(this);
  16341. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16342. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  16343. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  16344. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  16345. BfType* discriminatorType = NULL;
  16346. BfTypedValue rawPayload;
  16347. BfIRValue enumVal;
  16348. if (mCurTypeInstance->IsPayloadEnum())
  16349. {
  16350. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  16351. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  16352. enumTypedValue = LoadValue(enumTypedValue);
  16353. enumVal = enumTypedValue.mValue;
  16354. rawPayload = ExtractValue(GetThis(), NULL, 1);
  16355. }
  16356. else
  16357. enumVal = mBfIRBuilder->GetArgument(0);
  16358. Array<BfType*> paramTypes;
  16359. paramTypes.Add(stringType);
  16360. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16361. BfIRValue switchVal;
  16362. if (!mCurTypeInstance->IsValuelessType())
  16363. switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  16364. HashSet<int64> handledCases;
  16365. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16366. {
  16367. if (fieldInstance.mIsEnumPayloadCase)
  16368. {
  16369. int tagId = -fieldInstance.mDataIdx - 1;
  16370. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16371. mBfIRBuilder->AddBlock(caseBlock);
  16372. mBfIRBuilder->SetInsertPoint(caseBlock);
  16373. BF_ASSERT(discriminatorType->IsPrimitiveType());
  16374. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  16375. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16376. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16377. auto stringDestVal = LoadValue(stringDestAddr);
  16378. SizedArray<BfIRValue, 2> args;
  16379. args.Add(stringDestVal.mValue);
  16380. args.Add(caseStr);
  16381. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16382. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  16383. BF_ASSERT(payloadType->IsTuple());
  16384. if (payloadType->mFieldInstances.size() != 0)
  16385. {
  16386. auto payload = rawPayload;
  16387. if (payload.mType != payloadType)
  16388. {
  16389. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  16390. }
  16391. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  16392. SizedArray<BfIRValue, 2> irArgs;
  16393. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  16394. stringDestVal = LoadValue(stringDestAddr);
  16395. irArgs.Add(stringDestVal.mValue);
  16396. exprEvaluator.CreateCall(NULL, toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  16397. }
  16398. mBfIRBuilder->CreateBr(endBlock);
  16399. continue;
  16400. }
  16401. if (fieldInstance.mConstIdx == -1)
  16402. continue;
  16403. // Only allow compact 'ValA, ValB' enum declaration fields through
  16404. auto fieldDef = fieldInstance.GetFieldDef();
  16405. auto fieldDecl = fieldDef->mFieldDeclaration;
  16406. if ((fieldDecl == NULL) || (fieldDef->mTypeRef != NULL))
  16407. continue;
  16408. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  16409. if (!handledCases.TryAdd(constant->mInt64, NULL))
  16410. {
  16411. // Duplicate
  16412. continue;
  16413. }
  16414. if (switchVal)
  16415. {
  16416. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16417. mBfIRBuilder->AddBlock(caseBlock);
  16418. mBfIRBuilder->SetInsertPoint(caseBlock);
  16419. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  16420. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16421. }
  16422. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16423. mBfIRBuilder->CreateStore(caseStr, strVal);
  16424. mBfIRBuilder->CreateBr(appendBlock);
  16425. }
  16426. mBfIRBuilder->AddBlock(appendBlock);
  16427. mBfIRBuilder->SetInsertPoint(appendBlock);
  16428. SizedArray<BfIRValue, 2> args;
  16429. auto stringDestVal = LoadValue(stringDestAddr);
  16430. args.Add(stringDestVal.mValue);
  16431. args.Add(mBfIRBuilder->CreateLoad(strVal));
  16432. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16433. if (switchVal)
  16434. {
  16435. mBfIRBuilder->CreateBr(endBlock);
  16436. mBfIRBuilder->AddBlock(noMatchBlock);
  16437. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  16438. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  16439. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  16440. args.clear();
  16441. args.Add(int64Val);
  16442. stringDestVal = LoadValue(stringDestAddr);
  16443. args.Add(stringDestVal.mValue);
  16444. exprEvaluator.CreateCall(NULL, toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  16445. mBfIRBuilder->CreateBr(endBlock);
  16446. mBfIRBuilder->AddBlock(endBlock);
  16447. mBfIRBuilder->SetInsertPoint(endBlock);
  16448. }
  16449. }
  16450. void BfModule::EmitTupleToStringBody()
  16451. {
  16452. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16453. BfExprEvaluator exprEvaluator(this);
  16454. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16455. Array<BfType*> paramTypes;
  16456. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  16457. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16458. paramTypes.Clear();
  16459. paramTypes.Add(stringType);
  16460. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16461. auto _AppendChar = [&](char c)
  16462. {
  16463. SizedArray<BfIRValue, 2> args;
  16464. auto stringDestVal = LoadValue(stringDestRef);
  16465. args.Add(stringDestVal.mValue);
  16466. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  16467. exprEvaluator.CreateCall(NULL, appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  16468. };
  16469. int fieldIdx = 0;
  16470. auto thisValue = GetThis();
  16471. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  16472. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  16473. BfIRValue commaStr;
  16474. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  16475. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  16476. _AppendChar('(');
  16477. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16478. {
  16479. if (fieldInstance.mDataIdx == -1)
  16480. continue;
  16481. if (fieldIdx > 0)
  16482. {
  16483. if (!commaStr)
  16484. commaStr = GetStringObjectValue(", ");
  16485. SizedArray<BfIRValue, 2> args;
  16486. auto stringDestVal = LoadValue(stringDestRef);
  16487. args.Add(stringDestVal.mValue);
  16488. args.Add(commaStr);
  16489. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16490. }
  16491. fieldIdx++;
  16492. if (fieldInstance.mResolvedType->IsValuelessType())
  16493. continue;
  16494. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  16495. if (fieldValue.mType->IsWrappableType())
  16496. {
  16497. auto wrappedType = GetWrappedStructType(fieldValue.mType);
  16498. if ((wrappedType->IsTypedPrimitive()) || (wrappedType->IsValuelessType()))
  16499. {
  16500. fieldValue.mType = wrappedType;
  16501. }
  16502. else
  16503. {
  16504. fieldValue = MakeAddressable(fieldValue);
  16505. fieldValue.mType = wrappedType;
  16506. fieldValue.mValue = mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapTypeInstPtr(fieldValue.mType->ToTypeInstance()));
  16507. if (!wrappedType->IsValuelessType())
  16508. fieldValue.mKind = BfTypedValueKind_Addr;
  16509. }
  16510. }
  16511. auto typeInstance = fieldValue.mType->ToTypeInstance();
  16512. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  16513. {
  16514. BfExprEvaluator exprEvaluator(this);
  16515. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16516. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16517. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  16518. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  16519. methodMatcher.TryDevirtualizeCall(fieldValue);
  16520. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16521. BfResolvedArg resolvedArg;
  16522. auto stringDestVal = LoadValue(stringDestRef);
  16523. resolvedArg.mTypedValue = stringDestVal;
  16524. resolvedArg.mResolvedType = stringDestVal.mType;
  16525. resolvedArgs.Add(resolvedArg);
  16526. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16527. continue;
  16528. }
  16529. if (fieldValue.mType->IsObjectOrInterface())
  16530. {
  16531. fieldValue = LoadValue(fieldValue);
  16532. BF_ASSERT(!fieldValue.IsAddr());
  16533. SizedArray<BfIRValue, 2> args;
  16534. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16535. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16536. stringDestVal = LoadValue(stringDestVal);
  16537. args.Add(stringDestVal.mValue);
  16538. exprEvaluator.CreateCall(NULL, toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  16539. continue;
  16540. }
  16541. BfExprEvaluator exprEvaluator(this);
  16542. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16543. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16544. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  16545. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  16546. methodMatcher.TryDevirtualizeCall(fieldValue);
  16547. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  16548. {
  16549. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  16550. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  16551. // Just append the type name
  16552. String typeName = TypeToString(fieldInstance.mResolvedType);
  16553. auto strVal = GetStringObjectValue(typeName);
  16554. SizedArray<BfIRValue, 2> args;
  16555. auto stringDestVal = LoadValue(stringDestRef);
  16556. args.Add(stringDestVal.mValue);
  16557. args.Add(strVal);
  16558. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16559. continue;
  16560. }
  16561. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16562. BfResolvedArg resolvedArg;
  16563. auto stringDestVal = LoadValue(stringDestRef);
  16564. resolvedArg.mTypedValue = stringDestVal;
  16565. resolvedArg.mResolvedType = stringDestVal.mType;
  16566. resolvedArgs.Add(resolvedArg);
  16567. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16568. }
  16569. _AppendChar(')');
  16570. }
  16571. void BfModule::EmitIteratorBlock(bool& skipBody)
  16572. {
  16573. auto methodInstance = mCurMethodInstance;
  16574. auto methodDef = methodInstance->mMethodDef;
  16575. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16576. auto typeDef = mCurTypeInstance->mTypeDef;
  16577. BfType* innerRetType = NULL;
  16578. BfTypeInstance* usingInterface = NULL;
  16579. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  16580. if (retTypeInst != NULL)
  16581. {
  16582. if ((retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef)) ||
  16583. (retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumeratorTypeDef)))
  16584. {
  16585. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  16586. }
  16587. }
  16588. if (innerRetType == NULL)
  16589. {
  16590. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  16591. return;
  16592. }
  16593. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  16594. if (blockBody == NULL)
  16595. return;
  16596. }
  16597. void BfModule::EmitGCMarkAppended(BfTypedValue markVal)
  16598. {
  16599. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  16600. if (gcType == NULL)
  16601. return;
  16602. BfModuleMethodInstance markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "MarkAppendedObject", 1);
  16603. if (!markFromGCThreadMethodInstance)
  16604. return;
  16605. SizedArray<BfIRValue, 1> args;
  16606. args.push_back(mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16607. BfExprEvaluator exprEvaluator(this);
  16608. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16609. }
  16610. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  16611. {
  16612. auto fieldType = markVal.mType;
  16613. auto fieldTypeInst = fieldType->ToTypeInstance();
  16614. if (fieldType == NULL)
  16615. return;
  16616. if (!markVal.mType->IsComposite())
  16617. markVal = LoadValue(markVal);
  16618. BfExprEvaluator exprEvaluator(this);
  16619. PopulateType(markVal.mType, BfPopulateType_Data);
  16620. if (markVal.mType->IsObjectOrInterface())
  16621. {
  16622. BfIRValue val = markVal.mValue;
  16623. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  16624. SizedArray<BfIRValue, 1> args;
  16625. args.push_back(val);
  16626. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16627. }
  16628. else if (fieldType->IsSizedArray())
  16629. {
  16630. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)fieldType;
  16631. if (sizedArrayType->mElementType->WantsGCMarking())
  16632. {
  16633. BfTypedValue arrayValue = markVal;
  16634. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  16635. auto itr = CreateAlloca(intPtrType);
  16636. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  16637. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  16638. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  16639. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  16640. mBfIRBuilder->CreateBr(loopBB);
  16641. mBfIRBuilder->SetInsertPoint(loopBB);
  16642. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  16643. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  16644. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  16645. mBfIRBuilder->SetInsertPoint(bodyBB);
  16646. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16647. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16648. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  16649. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16650. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16651. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  16652. mBfIRBuilder->CreateStore(incValue, itr);
  16653. mBfIRBuilder->CreateBr(loopBB);
  16654. mBfIRBuilder->SetInsertPoint(doneBB);
  16655. }
  16656. }
  16657. else if ((fieldType->IsComposite()) && (!fieldType->IsTypedPrimitive()) && (fieldTypeInst != NULL))
  16658. {
  16659. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  16660. if (markMemberMethodInstance)
  16661. {
  16662. SizedArray<BfIRValue, 1> args;
  16663. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  16664. if (markVal.mType != methodOwner)
  16665. markVal = Cast(NULL, markVal, methodOwner);
  16666. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  16667. exprEvaluator.CreateCall(NULL, markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  16668. }
  16669. }
  16670. }
  16671. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  16672. {
  16673. Array<BfMethodInstance*> methodInstances;
  16674. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  16675. {
  16676. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  16677. auto chainedMethodInst = methodInstGroup.mDefault;
  16678. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  16679. {
  16680. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  16681. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  16682. {
  16683. methodInstances.push_back(chainedMethodInst);
  16684. }
  16685. }
  16686. }
  16687. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  16688. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  16689. {
  16690. bool isBetter;
  16691. bool isWorse;
  16692. CompareDeclTypes(mCurTypeInstance, lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  16693. if (isBetter == isWorse)
  16694. {
  16695. return false;
  16696. }
  16697. return isWorse;
  16698. });
  16699. if (reverse)
  16700. std::reverse(methodInstances.begin(), methodInstances.end());
  16701. for (auto chainedMethodInst : methodInstances)
  16702. {
  16703. auto declModule = this;
  16704. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  16705. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  16706. BfExprEvaluator exprEvaluator(this);
  16707. SizedArray<BfIRValue, 1> args;
  16708. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  16709. exprEvaluator.CreateCall(NULL, moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  16710. }
  16711. }
  16712. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  16713. {
  16714. BF_ASSERT(mCurMethodInstance->mIsReified);
  16715. if (mCurTypeInstance->mHotTypeData == NULL)
  16716. {
  16717. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  16718. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  16719. }
  16720. auto hotMethod = mCurMethodInstance->mHotMethod;
  16721. for (auto depData : hotMethod->mReferences)
  16722. {
  16723. // Only virtual decls are allowed to already be there
  16724. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  16725. }
  16726. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  16727. int prevSize = (int)hotMethod->mReferences.size();
  16728. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  16729. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  16730. refCount++;
  16731. hotMethod->mReferences.Reserve(refCount);
  16732. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  16733. {
  16734. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  16735. hotThis->mRefCount++;
  16736. hotMethod->mReferences.Insert(0, hotThis);
  16737. prevSize++;
  16738. }
  16739. for (auto val : builder->mAllocatedData)
  16740. {
  16741. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  16742. hotMethod->mReferences.Add(hotAllocation);
  16743. }
  16744. for (auto val : builder->mUsedData)
  16745. hotMethod->mReferences.Add(val);
  16746. for (auto val : builder->mCalledMethods)
  16747. hotMethod->mReferences.Add(val);
  16748. for (auto val : builder->mDevirtualizedCalledMethods)
  16749. {
  16750. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  16751. hotMethod->mReferences.Add(devirtualizedMethod);
  16752. }
  16753. for (auto val : builder->mFunctionPtrs)
  16754. {
  16755. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  16756. hotMethod->mReferences.Add(funcRef);
  16757. }
  16758. for (auto val : builder->mInnerMethods)
  16759. {
  16760. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  16761. hotMethod->mReferences.Add(innerMethod);
  16762. }
  16763. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  16764. {
  16765. auto depData = hotMethod->mReferences[refIdx];
  16766. BF_ASSERT(depData != NULL);
  16767. depData->mRefCount++;
  16768. }
  16769. }
  16770. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  16771. {
  16772. auto methodDef = methodInstance->mMethodDef;
  16773. auto methodDeclaration = methodDef->mMethodDeclaration;
  16774. bool isThisStruct = false;
  16775. if (thisType != NULL)
  16776. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  16777. int argIdx = 0;
  16778. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16779. argIdx++;
  16780. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16781. if (!methodDef->mIsStatic)
  16782. {
  16783. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16784. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16785. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  16786. paramVar->mIsBumpAlloc = true;
  16787. paramVar->mResolvedType = thisType;
  16788. paramVar->mName.Reference("this");
  16789. if (!thisType->IsValuelessType())
  16790. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16791. else
  16792. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  16793. if ((!mIsComptimeModule) && (thisType->IsSplattable()) && (methodInstance->AllowsSplatting(-1)))
  16794. {
  16795. if (!thisType->IsTypedPrimitive())
  16796. paramVar->mIsSplat = true;
  16797. }
  16798. else if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  16799. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  16800. auto thisTypeInst = thisType->ToTypeInstance();
  16801. paramVar->mIsStruct = isThisStruct;
  16802. paramVar->mAddr = BfIRValue();
  16803. paramVar->mIsThis = true;
  16804. paramVar->mParamIdx = -1;
  16805. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  16806. {
  16807. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  16808. }
  16809. else
  16810. {
  16811. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16812. }
  16813. paramVar->mReadFromId = -1;
  16814. paramVar->Init();
  16815. if (methodDeclaration == NULL)
  16816. UseDefaultSrcPos();
  16817. AddLocalVariableDef(paramVar);
  16818. if (!thisType->IsValuelessType())
  16819. {
  16820. if (wantsDIData)
  16821. {
  16822. BfType* thisPtrType = thisType;
  16823. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  16824. if (!thisType->IsValueType())
  16825. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  16826. else if (!paramVar->mIsSplat)
  16827. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  16828. diParams->push_back(diType);
  16829. }
  16830. if (paramVar->mIsSplat)
  16831. {
  16832. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16833. }
  16834. else
  16835. {
  16836. argIdx++;
  16837. if (loweredTypeCode2 != BfTypeCode_None)
  16838. argIdx++;
  16839. }
  16840. }
  16841. }
  16842. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16843. argIdx++;
  16844. bool hadParams = false;
  16845. bool hasDefault = false;
  16846. int compositeVariableIdx = -1;
  16847. int paramIdx = 0;
  16848. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16849. {
  16850. // We already issues a type error for this param if we had one in declaration processing
  16851. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  16852. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  16853. paramVar->mIsBumpAlloc = true;
  16854. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16855. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16856. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  16857. auto resolvedType = methodInstance->GetParamType(paramIdx);
  16858. if (resolvedType == NULL)
  16859. {
  16860. AssertErrorState();
  16861. paramVar->mParamFailed = true;
  16862. }
  16863. prevIgnoreErrors.Restore();
  16864. PopulateType(resolvedType, BfPopulateType_Declaration);
  16865. paramVar->mResolvedType = resolvedType;
  16866. int namePrefixCount = 0;
  16867. methodInstance->GetParamName(paramIdx, paramVar->mName, namePrefixCount);
  16868. paramVar->mNamePrefixCount = (uint8)namePrefixCount;
  16869. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  16870. if (!isParamSkipped)
  16871. {
  16872. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16873. if (resolvedType->IsMethodRef())
  16874. {
  16875. paramVar->mIsSplat = true;
  16876. }
  16877. else if ((!mIsComptimeModule) && (resolvedType->IsComposite()) && (resolvedType->IsSplattable()))
  16878. {
  16879. if (methodInstance->AllowsSplatting(paramIdx))
  16880. {
  16881. auto resolveTypeInst = resolvedType->ToTypeInstance();
  16882. if ((resolveTypeInst != NULL) && (resolveTypeInst->mIsCRepr))
  16883. paramVar->mIsSplat = true;
  16884. else
  16885. {
  16886. int splatCount = resolvedType->GetSplatCount();
  16887. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16888. paramVar->mIsSplat = true;
  16889. }
  16890. }
  16891. }
  16892. }
  16893. else
  16894. {
  16895. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  16896. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  16897. }
  16898. paramVar->mIsLowered = (!mIsComptimeModule) && resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  16899. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  16900. paramVar->mParamIdx = paramIdx;
  16901. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  16902. paramVar->mReadFromId = 0;
  16903. if (resolvedType->IsRef())
  16904. {
  16905. auto refType = (BfRefType*)resolvedType;
  16906. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  16907. if (refType->mRefKind == BfRefType::RefKind_In)
  16908. {
  16909. paramVar->mIsReadOnly = true;
  16910. }
  16911. }
  16912. else
  16913. {
  16914. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16915. if (methodDef->mMethodType != BfMethodType_Mixin)
  16916. paramVar->mIsReadOnly = true;
  16917. }
  16918. if (paramVar->mResolvedType->IsGenericParam())
  16919. {
  16920. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  16921. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  16922. {
  16923. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  16924. paramVar->mResolvedType = typedVal.mType;
  16925. paramVar->mConstValue = typedVal.mValue;
  16926. }
  16927. }
  16928. if (paramVar->mResolvedType->IsConstExprValue())
  16929. {
  16930. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  16931. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  16932. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  16933. BF_ASSERT(unspecParamType->IsGenericParam());
  16934. if (unspecParamType->IsGenericParam())
  16935. {
  16936. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  16937. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  16938. {
  16939. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  16940. if (genericParamInst->mTypeConstraint != NULL)
  16941. {
  16942. BfExprEvaluator exprEvaluator(this);
  16943. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  16944. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  16945. auto checkType = genericParamInst->mTypeConstraint;
  16946. if (checkType->IsTypedPrimitive())
  16947. checkType = checkType->GetUnderlyingType();
  16948. auto typedVal = exprEvaluator.mResult;
  16949. if ((typedVal) && (typedVal.mType != checkType))
  16950. typedVal = Cast(NULL, typedVal, checkType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  16951. if ((typedVal.mType == checkType) && (typedVal.mValue.IsConst()))
  16952. {
  16953. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  16954. paramVar->mConstValue = typedVal.mValue;
  16955. BF_ASSERT(paramVar->mConstValue.IsConst());
  16956. paramVar->mIsConst = true;
  16957. }
  16958. else
  16959. {
  16960. AssertErrorState();
  16961. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  16962. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  16963. paramVar->mIsConst = true;
  16964. }
  16965. if (paramVar->mResolvedType->IsObject())
  16966. {
  16967. BfTypedValue typedVal(paramVar->mConstValue, paramVar->mResolvedType);
  16968. FixValueActualization(typedVal);
  16969. if (typedVal.mValue.IsConst())
  16970. paramVar->mConstValue = typedVal.mValue;
  16971. }
  16972. }
  16973. }
  16974. }
  16975. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  16976. if (paramVar->mResolvedType->IsConstExprValue())
  16977. {
  16978. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  16979. //AssertErrorState();
  16980. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  16981. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  16982. paramVar->mIsConst = true;
  16983. }
  16984. }
  16985. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  16986. {
  16987. if (compositeVariableIdx == -1)
  16988. {
  16989. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  16990. BfLocalVariable* localVar = new BfLocalVariable();
  16991. auto paramInst = &methodInstance->mParams[paramIdx];
  16992. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  16993. localVar->mName = paramDef->mName;
  16994. localVar->mNamePrefixCount = paramDef->mNamePrefixCount;
  16995. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  16996. localVar->mCompositeCount = 0;
  16997. DoAddLocalVariable(localVar);
  16998. }
  16999. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  17000. paramVar->mIsImplicitParam = true;
  17001. }
  17002. if (!mCurTypeInstance->IsDelegateOrFunction())
  17003. CheckVariableDef(paramVar);
  17004. paramVar->Init();
  17005. AddLocalVariableDef(paramVar);
  17006. if (!isParamSkipped)
  17007. {
  17008. if (wantsDIData)
  17009. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  17010. if (paramVar->mIsSplat)
  17011. {
  17012. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17013. }
  17014. else
  17015. {
  17016. argIdx++;
  17017. }
  17018. if (loweredTypeCode2 != BfTypeCode_None)
  17019. argIdx++;
  17020. }
  17021. }
  17022. // Try to find an ending delegate params composite
  17023. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  17024. {
  17025. auto paramDef = methodDef->mParams.back();
  17026. if (paramDef->mParamKind == BfParamKind_Params)
  17027. {
  17028. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  17029. if (paramsType == NULL)
  17030. {
  17031. // Had error or 'var'
  17032. }
  17033. else if (paramsType->IsGenericParam())
  17034. {
  17035. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  17036. if (genericParamInstance->mTypeConstraint != NULL)
  17037. {
  17038. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  17039. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  17040. ((typeInstConstraint != NULL) &&
  17041. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  17042. {
  17043. BfLocalVariable* localVar = new BfLocalVariable();
  17044. localVar->mName = paramDef->mName;
  17045. localVar->mResolvedType = paramsType;
  17046. localVar->mCompositeCount = 0;
  17047. DoAddLocalVariable(localVar);
  17048. }
  17049. }
  17050. }
  17051. else if (paramsType->IsDelegate())
  17052. {
  17053. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  17054. if (invokeMethodInstance != NULL)
  17055. {
  17056. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  17057. // and wasn't cleared by the preceding loop
  17058. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  17059. BfLocalVariable* localVar = new BfLocalVariable();
  17060. localVar->mName = paramDef->mName;
  17061. localVar->mResolvedType = paramsType;
  17062. localVar->mCompositeCount = 0;
  17063. DoAddLocalVariable(localVar);
  17064. }
  17065. }
  17066. }
  17067. }
  17068. }
  17069. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  17070. {
  17071. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  17072. // return;
  17073. auto startMethodState = mCurMethodState;
  17074. auto _ClearState = [&]()
  17075. {
  17076. mCurMethodState->mLocalMethods.Clear();
  17077. for (auto& local : mCurMethodState->mLocals)
  17078. {
  17079. if (local->mIsBumpAlloc)
  17080. local->~BfLocalVariable();
  17081. else
  17082. delete local;
  17083. }
  17084. mCurMethodState->mLocals.Clear();
  17085. mCurMethodState->mLocalVarSet.Clear();
  17086. };
  17087. while (true)
  17088. {
  17089. bool didWork = false;
  17090. // 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
  17091. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  17092. // however (compiler bug), so this is the safest way
  17093. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  17094. {
  17095. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  17096. {
  17097. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  17098. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  17099. if (!mHadBuildError)
  17100. {
  17101. // Process as a closure - that allows us to look back and see the const locals and stuff
  17102. BfClosureState closureState;
  17103. mCurMethodState->mClosureState = &closureState;
  17104. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17105. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  17106. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  17107. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  17108. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  17109. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17110. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  17111. _ClearState();
  17112. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  17113. {
  17114. auto localVar = new BfLocalVariable();
  17115. *localVar = constLocal;
  17116. DoAddLocalVariable(localVar);
  17117. }
  17118. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  17119. bool doProcess = !mCompiler->mCanceling;
  17120. if (doProcess)
  17121. {
  17122. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  17123. ProcessMethod(deferredLocalMethod->mMethodInstance);
  17124. }
  17125. }
  17126. delete deferredLocalMethod;
  17127. mContext->CheckLockYield();
  17128. didWork = true;
  17129. }
  17130. mCurMethodState->mDeferredLocalMethods.Clear();
  17131. }
  17132. for (auto& kv : mCurMethodState->mLocalMethodCache)
  17133. {
  17134. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  17135. }
  17136. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  17137. {
  17138. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  17139. {
  17140. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  17141. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  17142. BfClosureState closureState;
  17143. mCurMethodState->mClosureState = &closureState;
  17144. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17145. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  17146. if (lambdaInstance->mClosureTypeInstance != NULL)
  17147. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  17148. else
  17149. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  17150. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17151. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  17152. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  17153. _ClearState();
  17154. for (auto& constLocal : lambdaInstance->mConstLocals)
  17155. {
  17156. //if (constLocal.mIsThis)
  17157. {
  17158. // Valueless 'this'
  17159. closureState.mConstLocals.Add(constLocal);
  17160. }
  17161. /*else
  17162. {
  17163. auto localVar = new BfLocalVariable();
  17164. *localVar = constLocal;
  17165. DoAddLocalVariable(localVar);
  17166. }*/
  17167. }
  17168. BfMethodInstanceGroup methodInstanceGroup;
  17169. methodInstanceGroup.mOwner = mCurTypeInstance;
  17170. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  17171. bool doProcess = !mCompiler->mCanceling;
  17172. if (doProcess)
  17173. {
  17174. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  17175. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17176. ProcessMethod(lambdaInstance->mMethodInstance);
  17177. lambdaInstance->mMethodInstance->mMethodInstanceGroup = NULL;
  17178. if (lambdaInstance->mDtorMethodInstance != NULL)
  17179. {
  17180. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17181. auto startMethodState2 = mCurMethodState;
  17182. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  17183. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = NULL;
  17184. }
  17185. }
  17186. didWork = true;
  17187. }
  17188. mContext->CheckLockYield();
  17189. mCurMethodState->mDeferredLambdaInstances.Clear();
  17190. }
  17191. if (!didWork)
  17192. break;
  17193. }
  17194. }
  17195. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance, bool isAppendObject)
  17196. {
  17197. if (checkType->IsComposite())
  17198. PopulateType(checkType, BfPopulateType_Data);
  17199. if (!checkType->WantsGCMarking())
  17200. return;
  17201. auto typeInstance = checkType->ToTypeInstance();
  17202. bool callMarkMethod = false;
  17203. // Call the actual marking method
  17204. if (memberDepth == 0)
  17205. {
  17206. // Don't call marking method on self
  17207. }
  17208. else if (checkType->IsObjectOrInterface())
  17209. {
  17210. if (!objectOffsets.Add(curOffset))
  17211. {
  17212. return;
  17213. }
  17214. callMarkMethod = true;
  17215. }
  17216. else if (checkType->IsSizedArray())
  17217. {
  17218. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  17219. if (sizedArrayType->mElementType->WantsGCMarking())
  17220. {
  17221. BfTypedValue arrayValue = thisValue;
  17222. if (thisValue.mType != checkType)
  17223. {
  17224. BfIRValue srcValue = thisValue.mValue;
  17225. if (curOffset != 0)
  17226. {
  17227. if (!thisValue.mType->IsPointer())
  17228. {
  17229. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17230. auto int8PtrType = CreatePointerType(int8Type);
  17231. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  17232. }
  17233. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  17234. }
  17235. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  17236. }
  17237. if (sizedArrayType->mElementCount > 6)
  17238. {
  17239. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  17240. auto itr = CreateAlloca(intPtrType);
  17241. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  17242. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  17243. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  17244. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  17245. mBfIRBuilder->CreateBr(loopBB);
  17246. mBfIRBuilder->SetInsertPoint(loopBB);
  17247. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  17248. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  17249. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  17250. mBfIRBuilder->SetInsertPoint(bodyBB);
  17251. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17252. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17253. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  17254. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17255. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17256. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  17257. mBfIRBuilder->CreateStore(incValue, itr);
  17258. mBfIRBuilder->CreateBr(loopBB);
  17259. mBfIRBuilder->SetInsertPoint(doneBB);
  17260. }
  17261. else
  17262. {
  17263. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  17264. {
  17265. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17266. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17267. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  17268. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17269. HashSet<int> objectOffsets;
  17270. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17271. }
  17272. }
  17273. }
  17274. }
  17275. else if (typeInstance != NULL)
  17276. {
  17277. typeInstance->mTypeDef->PopulateMemberSets();
  17278. BfMemberSetEntry* entry = NULL;
  17279. BfMethodDef* methodDef = NULL;
  17280. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  17281. {
  17282. methodDef = (BfMethodDef*)entry->mMemberDef;
  17283. if (methodDef->HasBody())
  17284. {
  17285. callMarkMethod = true;
  17286. }
  17287. }
  17288. }
  17289. if (callMarkMethod)
  17290. {
  17291. BfTypedValue markValue;
  17292. auto memberType = checkType;
  17293. if (memberType->IsObjectOrInterface())
  17294. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  17295. auto memberPtrType = CreatePointerType(memberType);
  17296. if (curOffset == 0)
  17297. {
  17298. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17299. }
  17300. else
  17301. {
  17302. if (!thisValue.mType->IsPointer())
  17303. {
  17304. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17305. auto int8PtrType = CreatePointerType(int8Type);
  17306. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  17307. }
  17308. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  17309. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17310. }
  17311. if (isAppendObject)
  17312. EmitGCMarkAppended(markValue);
  17313. else
  17314. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17315. return;
  17316. }
  17317. auto methodDef = mCurMethodInstance->mMethodDef;
  17318. if (checkType->IsPayloadEnum())
  17319. {
  17320. for (auto& fieldInst : typeInstance->mFieldInstances)
  17321. {
  17322. if (!fieldInst.mIsEnumPayloadCase)
  17323. continue;
  17324. auto fieldDef = fieldInst.GetFieldDef();
  17325. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17326. }
  17327. return;
  17328. }
  17329. if (typeInstance == NULL)
  17330. return;
  17331. for (auto& fieldInst : typeInstance->mFieldInstances)
  17332. {
  17333. auto fieldDef = fieldInst.GetFieldDef();
  17334. if (fieldDef == NULL)
  17335. continue;
  17336. if (fieldDef->mIsStatic)
  17337. continue;
  17338. if (typeInstance == mCurTypeInstance)
  17339. {
  17340. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  17341. // we may be marking member values that can never contain a value anyway, but this is benign
  17342. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17343. continue;
  17344. }
  17345. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance, fieldInst.IsAppendedObject());
  17346. }
  17347. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  17348. {
  17349. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17350. }
  17351. }
  17352. void BfModule::EmitGCMarkMembers()
  17353. {
  17354. auto methodDef = mCurMethodInstance->mMethodDef;
  17355. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  17356. BfModuleMethodInstance markFromGCThreadMethodInstance;
  17357. if (gcType != NULL)
  17358. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  17359. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  17360. {
  17361. if (mCurTypeInstance->IsBoxed())
  17362. {
  17363. // This already gets filled in by the normal boxed forwarding
  17364. }
  17365. else
  17366. {
  17367. auto thisValue = GetThis();
  17368. if (thisValue.IsSplat())
  17369. {
  17370. BfIRFunction func = mCurMethodInstance->mIRFunction;
  17371. int argIdx = 0;
  17372. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  17373. {
  17374. if (checkType->IsStruct())
  17375. {
  17376. auto checkTypeInstance = checkType->ToTypeInstance();
  17377. if (checkTypeInstance->mBaseType != NULL)
  17378. checkTypeLambda(checkTypeInstance->mBaseType);
  17379. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  17380. {
  17381. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  17382. if (fieldInstance->mDataIdx >= 0)
  17383. checkTypeLambda(fieldInstance->GetResolvedType());
  17384. }
  17385. }
  17386. else if (checkType->IsMethodRef())
  17387. {
  17388. BFMODULE_FATAL(this, "Not handled");
  17389. }
  17390. else if (checkType->WantsGCMarking())
  17391. {
  17392. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  17393. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17394. argIdx++;
  17395. }
  17396. };
  17397. checkTypeLambda(thisValue.mType);
  17398. }
  17399. else if (!methodDef->mIsStatic)
  17400. {
  17401. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  17402. {
  17403. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  17404. if (moduleMethodInst)
  17405. {
  17406. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  17407. bool wantsBaseMarking = true;
  17408. if (methodBaseType == mContext->mBfObjectType)
  17409. {
  17410. wantsBaseMarking = false;
  17411. PopulateType(methodBaseType);
  17412. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  17413. {
  17414. if ((fieldInstance.GetFieldDef()->mDeclaringType->IsExtension()) &&
  17415. (fieldInstance.mResolvedType->WantsGCMarking()))
  17416. wantsBaseMarking = true;
  17417. }
  17418. }
  17419. if (wantsBaseMarking)
  17420. {
  17421. auto thisValue = GetThis();
  17422. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  17423. SizedArray<BfIRValue, 1> args;
  17424. if ((!mIsComptimeModule) && (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1)))
  17425. {
  17426. BfExprEvaluator exprEvaluator(this);
  17427. exprEvaluator.SplatArgs(baseValue, args);
  17428. }
  17429. else
  17430. {
  17431. args.push_back(baseValue.mValue);
  17432. }
  17433. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  17434. }
  17435. }
  17436. }
  17437. }
  17438. if (!methodDef->mIsStatic)
  17439. {
  17440. HashSet<int> objectOffsets;
  17441. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  17442. }
  17443. else
  17444. {
  17445. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17446. {
  17447. if (thisValue.IsSplat())
  17448. break;
  17449. auto fieldDef = fieldInst.GetFieldDef();
  17450. if (fieldDef == NULL)
  17451. continue;
  17452. if (IsThreadLocal(&fieldInst))
  17453. continue;
  17454. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  17455. {
  17456. // For extensions, only handle these fields in the appropriate extension
  17457. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17458. continue;
  17459. if (!fieldInst.mFieldIncluded)
  17460. continue;
  17461. auto fieldType = fieldInst.mResolvedType;
  17462. auto fieldDef = fieldInst.GetFieldDef();
  17463. BfTypedValue markVal;
  17464. if (fieldDef->mIsConst)
  17465. continue;
  17466. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17467. continue;
  17468. mBfIRBuilder->PopulateType(fieldType);
  17469. if (fieldType->IsValuelessType())
  17470. continue;
  17471. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  17472. {
  17473. StringT<512> staticVarName;
  17474. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  17475. if (staticVarName.StartsWith('#'))
  17476. continue;
  17477. markVal = ReferenceStaticField(&fieldInst);
  17478. }
  17479. else if (!fieldDef->mIsStatic)
  17480. {
  17481. if (fieldInst.IsAppendedObject())
  17482. {
  17483. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst.mDataIdx);
  17484. auto val = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  17485. markVal = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst.mResolvedType)), fieldInst.mResolvedType);
  17486. }
  17487. else
  17488. {
  17489. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  17490. }
  17491. }
  17492. if (markVal)
  17493. {
  17494. if (fieldInst.IsAppendedObject())
  17495. EmitGCMarkAppended(markVal);
  17496. else
  17497. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  17498. }
  17499. }
  17500. }
  17501. }
  17502. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17503. CallChainedMethods(mCurMethodInstance, false);
  17504. }
  17505. }
  17506. }
  17507. void BfModule::EmitGCFindTLSMembers()
  17508. {
  17509. auto methodDef = mCurMethodInstance->mMethodDef;
  17510. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  17511. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  17512. BF_ASSERT(reportTLSMark);
  17513. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17514. {
  17515. auto fieldDef = fieldInst.GetFieldDef();
  17516. if (fieldDef == NULL)
  17517. continue;
  17518. if (!IsThreadLocal(&fieldInst))
  17519. continue;
  17520. // For extensions, only handle these fields in the appropriate extension
  17521. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17522. continue;
  17523. if (!fieldInst.mFieldIncluded)
  17524. continue;
  17525. if (fieldDef->mIsConst)
  17526. continue;
  17527. auto fieldType = fieldInst.mResolvedType;
  17528. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17529. continue;
  17530. if (fieldType->IsValuelessType())
  17531. continue;
  17532. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  17533. if (markVal)
  17534. {
  17535. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  17536. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  17537. SizedArray<BfIRValue, 2> llvmArgs;
  17538. llvmArgs.push_back(fieldRefPtr);
  17539. llvmArgs.push_back(markFuncPtr);
  17540. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  17541. }
  17542. }
  17543. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17544. CallChainedMethods(mCurMethodInstance, false);
  17545. }
  17546. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup, bool forceIRWrites)
  17547. {
  17548. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  17549. if (mIsComptimeModule)
  17550. {
  17551. BF_ASSERT(!mCompiler->IsAutocomplete());
  17552. }
  17553. if (mAwaitingInitFinish)
  17554. FinishInit();
  17555. if ((methodInstance->mIsReified) && (!mCompiler->mIsResolveOnly))
  17556. {
  17557. BfLogSysM("REIFIED(ProcessMethod): %s %p Module: %s\n", methodInstance->mMethodDef->mName.c_str(), methodInstance, mModuleName.c_str());
  17558. }
  17559. // Reify types that are actually used - they don't get reified during method declaration
  17560. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  17561. {
  17562. auto _CheckType = [&](BfType* type)
  17563. {
  17564. if (!type->IsReified())
  17565. PopulateType(type, BfPopulateType_Declaration);
  17566. };
  17567. _CheckType(methodInstance->mReturnType);
  17568. for (auto& param : methodInstance->mParams)
  17569. {
  17570. _CheckType(param.mResolvedType);
  17571. }
  17572. }
  17573. if (!methodInstance->mIsReified)
  17574. BF_ASSERT(!mIsReified);
  17575. BF_ASSERT((!methodInstance->GetOwner()->IsUnspecializedTypeVariation()) || (mIsComptimeModule));
  17576. if (methodInstance->mMethodInfoEx != NULL)
  17577. {
  17578. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  17579. {
  17580. if (methodGenericArg->IsMethodRef())
  17581. {
  17582. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  17583. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  17584. }
  17585. }
  17586. }
  17587. if (mBfIRBuilder == NULL)
  17588. {
  17589. BfLogSysM("ProcessMethod %p calling EnsureIRBuilder\n", methodInstance);
  17590. EnsureIRBuilder();
  17591. }
  17592. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, (mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized) && (!forceIRWrites));
  17593. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  17594. {
  17595. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  17596. }
  17597. SetAndRestoreValue<bool> prevIsClassifying;
  17598. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  17599. (mCompiler->mResolvePassData != NULL))
  17600. {
  17601. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  17602. prevIsClassifying.Init(mCompiler->mResolvePassData->mIsClassifying, false);
  17603. }
  17604. if (methodInstance->mHasBeenProcessed)
  17605. {
  17606. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  17607. return;
  17608. }
  17609. if (methodInstance->mFailedConstraints)
  17610. {
  17611. // The only way this should be able to happen is if we fail our generic param check
  17612. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  17613. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  17614. methodInstance->mHasBeenProcessed = true;
  17615. return;
  17616. }
  17617. if (HasExecutedOutput())
  17618. {
  17619. BF_ASSERT(mIsModuleMutable);
  17620. }
  17621. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  17622. if (!mIsComptimeModule)
  17623. {
  17624. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  17625. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  17626. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  17627. {
  17628. auto owningModule = methodInstance->GetOwner()->mModule;
  17629. if (owningModule->mIsScratchModule)
  17630. {
  17631. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  17632. }
  17633. else
  17634. {
  17635. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  17636. if (owningModule->mOnDemandMethodCount > 0)
  17637. owningModule->mOnDemandMethodCount--;
  17638. }
  17639. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  17640. VerifyOnDemandMethods();
  17641. }
  17642. }
  17643. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  17644. // self-referencing append allocations in ctor@calcAppend
  17645. methodInstance->mHasBeenProcessed = true;
  17646. mIncompleteMethodCount--;
  17647. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  17648. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  17649. auto methodDef = methodInstance->mMethodDef;
  17650. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17651. if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  17652. mBfIRBuilder->mIgnoreWrites = true;
  17653. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  17654. {
  17655. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  17656. // so we get the new vdata for it
  17657. methodInstance->GetOwner()->mDirty = true;
  17658. }
  17659. int dependentGenericStartIdx = 0;
  17660. if ((methodDef->mIsLocalMethod) && (mCurMethodState != NULL)) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  17661. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  17662. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  17663. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  17664. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  17665. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  17666. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  17667. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors);
  17668. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, mIsComptimeModule);
  17669. if ((!mIsComptimeModule) && (methodInstance->mIsReified) &&
  17670. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  17671. {
  17672. mCurTypeInstance->mHasBeenInstantiated = true;
  17673. }
  17674. // Warnings are shown in the capture phase
  17675. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  17676. mIgnoreWarnings = true;
  17677. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  17678. UseDefaultSrcPos();
  17679. if ((mIsComptimeModule) && (methodDef->mIsStatic))
  17680. {
  17681. PopulateType(mCurTypeInstance, BfPopulateType_AllowStaticMethods);
  17682. }
  17683. else
  17684. {
  17685. // We may not actually be populated in relatively rare autocompelte cases
  17686. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  17687. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  17688. }
  17689. BfAstNode* nameNode = NULL;
  17690. if (methodDeclaration != NULL)
  17691. {
  17692. nameNode = methodDeclaration->mNameNode;
  17693. if (nameNode == NULL)
  17694. {
  17695. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  17696. nameNode = ctorDeclaration->mThisToken;
  17697. }
  17698. }
  17699. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  17700. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) &&
  17701. (methodDef->mIdx >= 0) && (!methodInstance->mIsForeignMethodDef))
  17702. {
  17703. if (methodInstance->GetExplicitInterface() == NULL)
  17704. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  17705. else
  17706. {
  17707. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  17708. {
  17709. auto ifaceInst = ifaceEntry.mInterfaceType;
  17710. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  17711. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17712. if (methodInstance->GetExplicitInterface() != ifaceInst)
  17713. continue;
  17714. ifaceInst->mTypeDef->PopulateMemberSets();
  17715. BfMethodDef* nextMethod = NULL;
  17716. BfMemberSetEntry* entry = NULL;
  17717. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17718. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17719. while (nextMethod != NULL)
  17720. {
  17721. auto checkMethod = nextMethod;
  17722. nextMethod = nextMethod->mNextWithSameName;
  17723. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  17724. if (implMethodInst == methodInstance)
  17725. {
  17726. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  17727. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  17728. }
  17729. }
  17730. }
  17731. }
  17732. if (methodDef->mIsOverride)
  17733. {
  17734. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  17735. {
  17736. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  17737. if (ventry.mDeclaringMethod.mMethodNum == -1)
  17738. continue;
  17739. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  17740. if (virtMethod != NULL)
  17741. {
  17742. if (virtMethod == methodInstance)
  17743. {
  17744. // Is matching method
  17745. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  17746. {
  17747. auto baseType = mCurTypeInstance->mBaseType;
  17748. if (baseType != NULL)
  17749. {
  17750. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  17751. baseType = baseType->mBaseType;
  17752. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  17753. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  17754. }
  17755. }
  17756. break;
  17757. }
  17758. }
  17759. }
  17760. }
  17761. }
  17762. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d Incomplete:%d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified, mIncompleteMethodCount);
  17763. int importStrNum = -1;
  17764. auto importKind = methodInstance->GetImportKind();
  17765. if ((!mCompiler->mIsResolveOnly) &&
  17766. ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic)))
  17767. {
  17768. if (auto customAttr = methodInstance->GetCustomAttributes()->Get(mCompiler->mImportAttributeTypeDef))
  17769. {
  17770. if (customAttr->mCtorArgs.size() == 1)
  17771. {
  17772. auto fileNameArg = customAttr->mCtorArgs[0];
  17773. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  17774. if (constant != NULL)
  17775. {
  17776. if (!constant->IsNull())
  17777. importStrNum = constant->mInt32;
  17778. }
  17779. else
  17780. {
  17781. importStrNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  17782. }
  17783. if (importStrNum != -1)
  17784. {
  17785. if (!mStringPoolRefs.Contains(importStrNum))
  17786. mStringPoolRefs.Add(importStrNum);
  17787. }
  17788. }
  17789. }
  17790. }
  17791. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  17792. {
  17793. if (mBfIRBuilder->mIgnoreWrites)
  17794. return;
  17795. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  17796. if (!methodInstance->mIRFunction)
  17797. {
  17798. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  17799. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  17800. BF_ASSERT(dllImportGlobalVar || methodInstance->mHasFailed);
  17801. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  17802. }
  17803. if (HasCompiledOutput())
  17804. {
  17805. BfDllImportEntry dllImportEntry;
  17806. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  17807. dllImportEntry.mMethodInstance = mCurMethodInstance;
  17808. mDllImportEntries.push_back(dllImportEntry);
  17809. }
  17810. return;
  17811. }
  17812. StringT<512> mangledName;
  17813. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  17814. if (!methodInstance->mIRFunction)
  17815. {
  17816. bool isIntrinsic = false;
  17817. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  17818. }
  17819. if (methodInstance->mIsIntrinsic)
  17820. return;
  17821. if (mCurTypeInstance->IsFunction())
  17822. return;
  17823. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  17824. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  17825. if (methodDef->mBody != NULL)
  17826. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17827. else if (methodDeclaration != NULL)
  17828. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17829. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17830. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  17831. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17832. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17833. if ((mCurMethodState == NULL) && (!IsInSpecializedSection())) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  17834. {
  17835. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()))
  17836. {
  17837. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(methodDef->mBody))
  17838. sourceClassifier->VisitChildNoRef(methodDef->mBody);
  17839. }
  17840. }
  17841. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  17842. BfMethodState methodState;
  17843. if (mCurMethodState != NULL)
  17844. methodState.mClosureState = mCurMethodState->mClosureState;
  17845. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  17846. {
  17847. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  17848. if (methodInstance->mHotMethod == NULL)
  17849. CheckHotMethod(methodInstance, mangledName);
  17850. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  17851. }
  17852. methodState.mPrevMethodState = mCurMethodState;
  17853. methodState.mMethodInstance = methodInstance;
  17854. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17855. if (methodInstance->GetCustomAttributes() != NULL)
  17856. {
  17857. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  17858. if (typeOptionsIdx != -1)
  17859. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  17860. }
  17861. BfTypeState typeState(mCurTypeInstance);
  17862. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  17863. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  17864. BfMethodInstance* unspecializedMethodInstance = NULL;
  17865. if ((prevMethodState.mPrevVal != NULL) &&
  17866. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  17867. {
  17868. // This is 'inner' (probably a closure) - use binding from outer function
  17869. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  17870. }
  17871. else if ((methodInstance->mIsUnspecialized) ||
  17872. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  17873. {
  17874. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17875. }
  17876. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  17877. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation || mIsComptimeModule) && (!methodInstance->mMethodDef->mIsLocalMethod) && (!methodInstance->mMethodDef->mDeclaringType->IsEmitted()))))
  17878. {
  17879. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  17880. if ((mIsComptimeModule) && (!unspecializedMethodInstance->mHasBeenProcessed))
  17881. {
  17882. // This will have already been populated by CeMachine
  17883. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17884. }
  17885. else
  17886. {
  17887. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  17888. if (!unspecializedMethodInstance->mHasBeenProcessed)
  17889. {
  17890. // Make sure the unspecialized method is processed so we can take its bindings
  17891. // Clear mCurMethodState so we don't think we're in a local method
  17892. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  17893. if (unspecializedMethodInstance->mMethodProcessRequest == NULL)
  17894. unspecializedMethodInstance->mDeclModule->mIncompleteMethodCount++;
  17895. mContext->ProcessMethod(unspecializedMethodInstance);
  17896. }
  17897. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17898. }
  17899. }
  17900. if (methodDef->mMethodType == BfMethodType_Operator)
  17901. {
  17902. auto operatorDef = (BfOperatorDef*) methodDef;
  17903. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  17904. auto paramErrorRefNode = refNode;
  17905. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  17906. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  17907. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  17908. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  17909. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  17910. {
  17911. if (methodDef->mParams.size() != 2)
  17912. {
  17913. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  17914. }
  17915. else
  17916. {
  17917. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17918. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17919. checkParam0 = checkParam0->GetUnderlyingType();
  17920. auto checkParam1 = mCurMethodInstance->GetParamType(1);
  17921. if ((checkParam1->IsRef()) && (!checkParam1->IsOut()))
  17922. checkParam1 = checkParam1->GetUnderlyingType();
  17923. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  17924. (checkParam1 != mCurTypeInstance) && (!checkParam1->IsSelf()))
  17925. {
  17926. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  17927. }
  17928. }
  17929. BfType* wantType = NULL;
  17930. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  17931. {
  17932. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  17933. }
  17934. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  17935. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  17936. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  17937. }
  17938. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  17939. {
  17940. if (methodDef->mIsStatic)
  17941. {
  17942. if (methodDef->mParams.size() != 1)
  17943. {
  17944. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  17945. }
  17946. else
  17947. {
  17948. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17949. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17950. checkParam0 = checkParam0->GetUnderlyingType();
  17951. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()))
  17952. {
  17953. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  17954. }
  17955. }
  17956. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  17957. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  17958. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  17959. {
  17960. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  17961. }
  17962. }
  17963. else
  17964. {
  17965. if (methodDef->mParams.size() != 0)
  17966. {
  17967. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  17968. }
  17969. if (!mCurMethodInstance->mReturnType->IsVoid())
  17970. {
  17971. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  17972. }
  17973. }
  17974. }
  17975. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  17976. {
  17977. if (methodDef->mParams.size() != 1)
  17978. {
  17979. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  17980. }
  17981. if (!mCurMethodInstance->mReturnType->IsVoid())
  17982. {
  17983. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  17984. }
  17985. }
  17986. else // Conversion
  17987. {
  17988. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  17989. {
  17990. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  17991. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  17992. }
  17993. if (methodDef->mParams.size() != 1)
  17994. {
  17995. auto refNode = paramErrorRefNode;
  17996. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  17997. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  17998. Fail("Conversion operators must declare one parameter", refNode);
  17999. }
  18000. else if ((methodInstance->mMethodInfoEx == NULL) ||
  18001. (methodInstance->mMethodInfoEx->mMethodGenericArguments.IsEmpty()) ||
  18002. ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation)))
  18003. {
  18004. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18005. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18006. checkParam0 = checkParam0->GetUnderlyingType();
  18007. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  18008. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  18009. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  18010. if (checkParam0 == mCurMethodInstance->mReturnType)
  18011. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  18012. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  18013. // happened here
  18014. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (checkParam0 != mContext->mBfObjectType)))
  18015. {
  18016. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  18017. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, checkParam0->ToTypeInstance());
  18018. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  18019. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  18020. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  18021. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  18022. }
  18023. }
  18024. }
  18025. }
  18026. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mBfIRBuilder->mIgnoreWrites) && (mHasFullDebugInfo);
  18027. if (methodDef->mMethodType == BfMethodType_Mixin)
  18028. wantsDIData = false;
  18029. if (mCurTypeInstance->IsUnspecializedType())
  18030. wantsDIData = false;
  18031. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  18032. wantsDIData = false;
  18033. bool wantsDIVariables = wantsDIData;
  18034. if (methodDef->mIsExtern)
  18035. wantsDIVariables = false;
  18036. SizedArray<BfIRMDNode, 8> diParams;
  18037. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  18038. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  18039. BfType* thisType = NULL;
  18040. if (!methodDef->mIsStatic)
  18041. {
  18042. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  18043. thisType = methodState.mClosureState->mClosureType;
  18044. else
  18045. thisType = mCurTypeInstance;
  18046. }
  18047. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  18048. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  18049. //////////////////////////////////////////////////////////////////////////
  18050. //
  18051. {
  18052. if (methodDeclaration != NULL)
  18053. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18054. else if (methodDef->mBody != NULL)
  18055. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18056. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18057. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  18058. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18059. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18060. }
  18061. BfIRMDNode diFunction;
  18062. if (wantsDIData)
  18063. {
  18064. BP_ZONE("BfModule::DoMethodDeclaration.DISetup");
  18065. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  18066. int defLine = mCurFilePosition.mCurLine;
  18067. if (mDICompileUnit)
  18068. {
  18069. int flags = 0;
  18070. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  18071. if (methodDef->mProtection == BfProtection_Public)
  18072. flags = llvm::DINode::FlagPublic;
  18073. else if (methodDef->mProtection == BfProtection_Protected)
  18074. flags = llvm::DINode::FlagProtected;
  18075. else
  18076. flags = llvm::DINode::FlagPrivate;
  18077. if (methodDef->mIsOverride)
  18078. {
  18079. //flags |= llvm::DINode::FlagVirtual;
  18080. }
  18081. else if (methodDef->mIsVirtual)
  18082. flags |= llvm::DINode::FlagIntroducedVirtual;
  18083. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  18084. flags |= llvm::DINode::FlagStaticMember;
  18085. else
  18086. {
  18087. if ((mCurTypeInstance->IsValuelessType()) ||
  18088. ((!mIsComptimeModule) && (mCurTypeInstance->IsSplattable())))
  18089. flags |= llvm::DINode::FlagStaticMember;
  18090. }
  18091. flags |= llvm::DINode::FlagPrototyped;
  18092. if (methodDef->mMethodType == BfMethodType_Ctor)
  18093. {
  18094. flags |= llvm::DINode::FlagArtificial;
  18095. }
  18096. auto llvmFunction = methodInstance->mIRFunction;
  18097. SizedArray<BfIRMDNode, 1> genericArgs;
  18098. SizedArray<BfIRValue, 1> genericConstValueArgs;
  18099. String methodName;
  18100. if (methodInstance->GetForeignType() != NULL)
  18101. {
  18102. methodName += TypeToString(methodInstance->GetForeignType());
  18103. methodName += ".";
  18104. }
  18105. if (methodInstance->GetExplicitInterface() != NULL)
  18106. {
  18107. methodName += TypeToString(methodInstance->GetExplicitInterface());
  18108. methodName += ".";
  18109. }
  18110. methodName += methodDef->mName;
  18111. if (methodInstance->GetNumGenericArguments() != 0)
  18112. {
  18113. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  18114. {
  18115. if (genericArg->IsConstExprValue())
  18116. {
  18117. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  18118. while (genericConstValueArgs.size() < genericArgs.size())
  18119. genericConstValueArgs.push_back(BfIRValue());
  18120. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  18121. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  18122. }
  18123. else
  18124. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  18125. }
  18126. methodName += "<";
  18127. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  18128. {
  18129. if (i > 0)
  18130. methodName += ", ";
  18131. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  18132. methodName += TypeToString(type);
  18133. }
  18134. methodName += ">";
  18135. }
  18136. if ((methodName.empty()) && (methodDeclaration != NULL))
  18137. {
  18138. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18139. {
  18140. methodName += "operator";
  18141. if (operatorDecl->mIsConvOperator)
  18142. {
  18143. methodName += " ";
  18144. methodName += TypeToString(methodInstance->mReturnType);
  18145. }
  18146. else if (operatorDecl->mOpTypeToken != NULL)
  18147. methodName += operatorDecl->mOpTypeToken->ToString();
  18148. }
  18149. }
  18150. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  18151. methodName += "$CHK";
  18152. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  18153. methodName += "$UCHK";
  18154. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18155. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18156. // defLine + 1, diFuncType, false, true,
  18157. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  18158. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  18159. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18160. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18161. defLine + 1, diFuncType, false, true,
  18162. llvm::dwarf::DW_VIRTUALITY_none,
  18163. 0,
  18164. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18165. }
  18166. else
  18167. {
  18168. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18169. }
  18170. }
  18171. //////////////////////////////////////////////////////////////////////////
  18172. // Head and Init get rolled into Entry afterwards.
  18173. methodState.mIRFunction = methodInstance->mIRFunction;
  18174. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  18175. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  18176. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  18177. methodState.mCurScope->mDIScope = diFunction;
  18178. auto llvmEntryBlock = methodState.mIREntryBlock;
  18179. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  18180. if (methodDef->mName == "__MALFORMED")
  18181. {
  18182. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  18183. mBfIRBuilder->SetInsertPoint(newBlock);
  18184. }
  18185. if (methodDef->mBody != NULL)
  18186. {
  18187. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18188. }
  18189. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  18190. {
  18191. // We want to be able to step into delegate invokes -- we actually step over them
  18192. if (methodDef->mName != "Invoke")
  18193. {
  18194. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18195. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  18196. }
  18197. }
  18198. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18199. mBfIRBuilder->ClearDebugLocation();
  18200. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  18201. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  18202. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  18203. {
  18204. int localIdx = 0;
  18205. int argIdx = 0;
  18206. Array<BfIRValue> splatAddrValues;
  18207. for ( ; argIdx < irParamCount; localIdx++)
  18208. {
  18209. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18210. if ((isThis) && (thisType->IsValuelessType()))
  18211. isThis = false;
  18212. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() == argIdx))
  18213. {
  18214. argIdx++;
  18215. if (argIdx == irParamCount)
  18216. break;
  18217. }
  18218. BfLocalVariable* paramVar = NULL;
  18219. while (true)
  18220. {
  18221. BF_ASSERT(localIdx < methodState.mLocals.size());
  18222. paramVar = methodState.mLocals[localIdx];
  18223. if ((paramVar->mCompositeCount == -1) &&
  18224. (!paramVar->mIsConst) &&
  18225. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  18226. break;
  18227. localIdx++;
  18228. }
  18229. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  18230. {
  18231. paramVar->mIsReadOnly = true;
  18232. }
  18233. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) ||
  18234. ((!mIsComptimeModule) && (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter)));
  18235. if (paramVar->mResolvedType->IsMethodRef())
  18236. wantsAddr = false;
  18237. // if ((methodDef->mHasAppend) && (argIdx == 1))
  18238. // {
  18239. // BF_ASSERT(paramVar->mName == "appendIdx");
  18240. // wantsAddr = true;
  18241. // }
  18242. if (paramVar->mIsSplat)
  18243. {
  18244. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18245. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18246. BfTypeUtils::SplatIterate([&](BfType* checkType)
  18247. {
  18248. BfIRType splatIRType;
  18249. if (checkType->IsComposite())
  18250. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  18251. else
  18252. splatIRType = mBfIRBuilder->MapType(checkType);
  18253. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  18254. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  18255. if (!paramVar->mAddr)
  18256. paramVar->mAddr = allocaInst;
  18257. if (WantsLifetimes())
  18258. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18259. splatAddrValues.push_back(allocaInst);
  18260. }, paramVar->mResolvedType);
  18261. mBfIRBuilder->SetInsertPoint(prevInsert);
  18262. }
  18263. else if (isThis)
  18264. {
  18265. if (wantsAddr)
  18266. {
  18267. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18268. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18269. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  18270. if (paramVar->mIsSplat)
  18271. {
  18272. //
  18273. }
  18274. else
  18275. {
  18276. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  18277. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  18278. wantPtr = true;
  18279. if (wantPtr)
  18280. {
  18281. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  18282. }
  18283. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  18284. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18285. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  18286. paramVar->mAddr = allocaInst;
  18287. if (WantsLifetimes())
  18288. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18289. }
  18290. mBfIRBuilder->SetInsertPoint(prevInsert);
  18291. }
  18292. }
  18293. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  18294. {
  18295. // Address doesn't change so we don't have to alloca it
  18296. BfIRType allocType;
  18297. int alignSize = mSystem->mPtrSize;
  18298. if (paramVar->mResolvedType->IsRef())
  18299. {
  18300. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18301. }
  18302. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  18303. {
  18304. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18305. alignSize = paramVar->mResolvedType->mAlign;
  18306. }
  18307. else
  18308. {
  18309. paramVar->mHasLocalStructBacking = true;
  18310. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  18311. if (typeInst != NULL)
  18312. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  18313. else
  18314. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  18315. }
  18316. if (wantsAddr)
  18317. {
  18318. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18319. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18320. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18321. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  18322. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18323. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  18324. paramVar->mAddr = allocaInst;
  18325. mBfIRBuilder->SetInsertPoint(prevInsert);
  18326. if (WantsLifetimes())
  18327. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18328. }
  18329. }
  18330. else if (wantsAddr)
  18331. {
  18332. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  18333. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18334. paramVar->mAddr = allocaInst;
  18335. }
  18336. if (paramVar->mIsSplat)
  18337. {
  18338. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18339. }
  18340. else if (paramVar->mIsLowered)
  18341. {
  18342. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18343. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18344. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18345. argIdx++;
  18346. if (loweredTypeCode2 != BfTypeCode_None)
  18347. argIdx++;
  18348. }
  18349. else
  18350. {
  18351. argIdx++;
  18352. }
  18353. }
  18354. if (methodDef->mBody != NULL)
  18355. UpdateSrcPos(methodDef->mBody);
  18356. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18357. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18358. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18359. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  18360. localIdx = 0;
  18361. argIdx = 0;
  18362. int splatAddrIdx = 0;
  18363. while (localIdx < (int)methodState.mLocals.size())
  18364. {
  18365. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  18366. argIdx++;
  18367. int curLocalIdx = localIdx++;
  18368. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  18369. if (paramVar->mIsConst)
  18370. continue;
  18371. if (!paramVar->IsParam())
  18372. continue;
  18373. if (paramVar->mCompositeCount != -1)
  18374. continue;
  18375. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18376. if ((isThis) && (thisType->IsValuelessType()))
  18377. isThis = false;
  18378. if (paramVar->mValue.IsArg())
  18379. BF_ASSERT(paramVar->mValue.mId == argIdx);
  18380. BfIRMDNode diVariable;
  18381. if (wantsDIData)
  18382. {
  18383. String paramName = paramVar->mName;
  18384. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18385. if (isThis)
  18386. {
  18387. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  18388. paramName = "__closure";
  18389. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18390. {
  18391. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18392. bool wantRef = paramVar->mResolvedType->IsComposite();
  18393. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  18394. wantRef = true;
  18395. if (wantRef)
  18396. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18397. }
  18398. else if (!paramVar->mResolvedType->IsValueType())
  18399. {
  18400. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  18401. }
  18402. }
  18403. else
  18404. {
  18405. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18406. {
  18407. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18408. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18409. diType = mBfIRBuilder->DbgCreateConstType(diType);
  18410. }
  18411. }
  18412. if (!paramVar->mIsSplat)
  18413. {
  18414. if ((paramVar->mParamIdx >= 0) && (paramVar->mParamIdx < methodInstance->mDefaultValues.mSize))
  18415. {
  18416. auto defaultValue = methodInstance->mDefaultValues[paramVar->mParamIdx];
  18417. auto constant = mCurTypeInstance->mConstHolder->GetConstant(defaultValue.mValue);
  18418. if ((constant != NULL) &&
  18419. ((BfIRConstHolder::IsIntable(constant->mTypeCode)) || (BfIRConstHolder::IsFloat(constant->mTypeCode))))
  18420. {
  18421. int64 writeVal = constant->mInt64;
  18422. if (constant->mTypeCode == BfTypeCode_Float)
  18423. {
  18424. // We need to do this because Singles are stored in mDouble, so we need to reduce here
  18425. float floatVal = (float)constant->mDouble;
  18426. writeVal = *(uint32*)&floatVal;
  18427. }
  18428. if (writeVal < 0)
  18429. paramName += StrFormat("$_%llu", -writeVal);
  18430. else
  18431. paramName += StrFormat("$%llu", writeVal);
  18432. }
  18433. }
  18434. if (paramVar->mResolvedType->IsValuelessType())
  18435. {
  18436. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  18437. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18438. }
  18439. else if (paramVar->mIsImplicitParam)
  18440. {
  18441. // Annotate this specially?
  18442. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18443. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18444. }
  18445. else
  18446. {
  18447. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18448. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18449. }
  18450. paramVar->mDbgVarInst = diVariable;
  18451. }
  18452. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  18453. {
  18454. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  18455. // {
  18456. // // Only add this placeholder if we don't have any values
  18457. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  18458. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18459. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  18460. // }
  18461. }
  18462. }
  18463. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  18464. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  18465. {
  18466. // Write our argument value into the .addr
  18467. mBfIRBuilder->ClearDebugLocation();
  18468. if (paramVar->mIsSplat)
  18469. {
  18470. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18471. //
  18472. }
  18473. else
  18474. {
  18475. bool handled = false;
  18476. if (paramVar->mIsLowered)
  18477. {
  18478. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18479. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18480. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  18481. {
  18482. BfIRValue targetAddr = paramVar->mAddr;
  18483. bool isTempTarget = false;
  18484. int loweredSize = mBfIRBuilder->GetSize(loweredTypeCode) + mBfIRBuilder->GetSize(loweredTypeCode2);
  18485. if (paramVar->mResolvedType->mSize < loweredSize)
  18486. {
  18487. isTempTarget = true;
  18488. targetAddr = CreateAlloca(GetPrimitiveType(BfTypeCode_Int8), true, NULL, GetConstValue(loweredSize));
  18489. mBfIRBuilder->SetAllocaAlignment(targetAddr,
  18490. BF_MAX(paramVar->mResolvedType->mAlign,
  18491. BF_MAX(mBfIRBuilder->GetSize(loweredTypeCode), mBfIRBuilder->GetSize(loweredTypeCode2))));
  18492. }
  18493. // We have a lowered type coming in, so we have to cast the .addr before storing
  18494. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  18495. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  18496. auto primPtrVal = mBfIRBuilder->CreateBitCast(targetAddr, primPtrType);
  18497. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, mCurTypeInstance->mAlign);
  18498. if (loweredTypeCode2 != BfTypeCode_None)
  18499. {
  18500. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  18501. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  18502. BfIRValue primPtrVal2;
  18503. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  18504. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  18505. else
  18506. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  18507. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  18508. }
  18509. if (isTempTarget)
  18510. {
  18511. auto castedTempPtr = mBfIRBuilder->CreateBitCast(targetAddr, mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType)));
  18512. auto tempVal = mBfIRBuilder->CreateAlignedLoad(castedTempPtr, paramVar->mResolvedType->mAlign);
  18513. mBfIRBuilder->CreateAlignedStore(tempVal, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  18514. }
  18515. // We don't want to allow directly using value
  18516. paramVar->mValue = BfIRValue();
  18517. handled = true;
  18518. }
  18519. else
  18520. {
  18521. BF_ASSERT("Expected lowered");
  18522. }
  18523. }
  18524. if (!handled)
  18525. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  18526. }
  18527. }
  18528. if (methodDef->mBody != NULL)
  18529. UpdateSrcPos(methodDef->mBody);
  18530. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  18531. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  18532. else if (methodDeclaration == NULL)
  18533. UseDefaultSrcPos();
  18534. // Write our argument value into the .addr
  18535. if (paramVar->mIsSplat)
  18536. {
  18537. int splatComponentIdx = 0;
  18538. auto curArgIdx = argIdx;
  18539. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  18540. {
  18541. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  18542. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  18543. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  18544. mBfIRBuilder->ClearDebugLocation(storeInst);
  18545. if (wantsDIData)
  18546. {
  18547. BfIRMDNode diType;
  18548. if (checkType->IsComposite())
  18549. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  18550. else
  18551. diType = mBfIRBuilder->DbgGetType(checkType);
  18552. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18553. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18554. if (wantsDIVariables)
  18555. {
  18556. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  18557. }
  18558. }
  18559. curArgIdx++;
  18560. splatComponentIdx++;
  18561. };
  18562. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  18563. {
  18564. if (checkType->IsStruct())
  18565. {
  18566. auto checkTypeInstance = checkType->ToTypeInstance();
  18567. if (checkTypeInstance->mBaseType != NULL)
  18568. {
  18569. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  18570. }
  18571. if (checkTypeInstance->mIsUnion)
  18572. {
  18573. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  18574. if (!unionInnerType->IsValuelessType())
  18575. {
  18576. _FinishSplatsIterate(unionInnerType, name + "$u");
  18577. }
  18578. if (checkTypeInstance->IsEnum())
  18579. {
  18580. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  18581. _FinishSplatsIterate(dscrType, name + "$d");
  18582. }
  18583. }
  18584. else
  18585. {
  18586. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  18587. {
  18588. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  18589. auto fieldDef = fieldInstance->GetFieldDef();
  18590. if (fieldInstance->mDataIdx >= 0)
  18591. {
  18592. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  18593. }
  18594. }
  18595. }
  18596. }
  18597. else if (checkType->IsMethodRef())
  18598. {
  18599. auto methodRefType = (BfMethodRefType*)checkType;
  18600. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  18601. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  18602. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  18603. // {
  18604. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  18605. // if (!paramType->IsValuelessType())
  18606. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  18607. // }
  18608. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  18609. {
  18610. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  18611. String paramName = methodInstance->GetParamName(paramIdx);
  18612. if (paramName == "this")
  18613. paramName = "__this";
  18614. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  18615. {
  18616. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  18617. }
  18618. else
  18619. {
  18620. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  18621. }
  18622. }
  18623. }
  18624. else if (!checkType->IsValuelessType())
  18625. {
  18626. _FinishSplats(checkType, name);
  18627. }
  18628. };
  18629. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18630. if (!paramVar->mConstValue)
  18631. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  18632. }
  18633. BfIRValue declareCall;
  18634. if (diVariable)
  18635. {
  18636. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  18637. {
  18638. if (!paramVar->mAddr)
  18639. {
  18640. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  18641. {
  18642. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  18643. {
  18644. // We don't need to set the location for this
  18645. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  18646. }
  18647. }
  18648. else
  18649. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  18650. }
  18651. else
  18652. {
  18653. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  18654. }
  18655. }
  18656. }
  18657. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  18658. {
  18659. // We don't allow actually assignment to "this", so we just do a single load
  18660. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  18661. // we need to store it in the stack frame for debugging purposes
  18662. auto loadedThis = mBfIRBuilder->CreateAlignedLoad(paramVar->mAddr/*, "this"*/, paramVar->mResolvedType->mAlign);
  18663. mBfIRBuilder->ClearDebugLocation(loadedThis);
  18664. paramVar->mValue = loadedThis;
  18665. }
  18666. if ((wantsDIData) && (declareCall))
  18667. mBfIRBuilder->UpdateDebugLocation(declareCall);
  18668. if (paramVar->mIsSplat)
  18669. {
  18670. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18671. }
  18672. else if (paramVar->mIsLowered)
  18673. {
  18674. argIdx++;
  18675. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18676. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18677. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18678. if (loweredTypeCode2 != BfTypeCode_None)
  18679. argIdx++;
  18680. }
  18681. else if (!paramVar->mResolvedType->IsValuelessType())
  18682. {
  18683. argIdx++;
  18684. }
  18685. }
  18686. if (wantsDIData)
  18687. {
  18688. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  18689. }
  18690. }
  18691. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  18692. {
  18693. auto paramVar = mCurMethodState->mLocals[varIdx];
  18694. // 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
  18695. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  18696. // if (paramVar->mIsSplat)
  18697. // {
  18698. // if (wantsDIVariables)
  18699. // {
  18700. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  18701. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  18702. // }
  18703. // }
  18704. if (paramVar->mResolvedType->IsValuelessType())
  18705. {
  18706. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  18707. {
  18708. // Only add this placeholder if we don't have any values
  18709. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18710. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  18711. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18712. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  18713. }
  18714. }
  18715. }
  18716. if (IsTargetingBeefBackend())
  18717. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  18718. if (methodState.mClosureState != NULL)
  18719. {
  18720. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  18721. {
  18722. BfLocalVariable* localVar = new BfLocalVariable();
  18723. *localVar = constLocal;
  18724. localVar->mIsBumpAlloc = false;
  18725. AddLocalVariableDef(localVar, true);
  18726. }
  18727. }
  18728. bool wantsRemoveBody = false;
  18729. bool skipBody = false;
  18730. bool skipUpdateSrcPos = false;
  18731. bool skipEndChecks = false;
  18732. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  18733. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18734. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  18735. hasExternSpecifier = true;
  18736. // Allocate, clear, set classVData
  18737. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  18738. {
  18739. CreateStaticCtor();
  18740. }
  18741. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  18742. {
  18743. skipBody = true;
  18744. skipEndChecks = true;
  18745. if (HasExecutedOutput())
  18746. {
  18747. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18748. mBfIRBuilder->ClearDebugLocation();
  18749. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  18750. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  18751. PopulateType(innerType, BfPopulateType_DataAndMethods);
  18752. mBfIRBuilder->PopulateType(mCurTypeInstance);
  18753. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  18754. if (methodInstance->mIsForeignMethodDef)
  18755. {
  18756. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  18757. }
  18758. BfTypeVector methodGenericArguments;
  18759. if (methodInstance->mMethodInfoEx != NULL)
  18760. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  18761. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  18762. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  18763. {
  18764. if (!methodInstance->mReturnType->IsValuelessType())
  18765. {
  18766. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  18767. CreateReturn(retVal);
  18768. }
  18769. else
  18770. mBfIRBuilder->CreateRetVoid();
  18771. }
  18772. else
  18773. {
  18774. auto innerMethodDef = innerMethodInstance.mMethodInstance->mMethodDef;
  18775. BF_ASSERT(innerMethodDef == methodDef);
  18776. SizedArray<BfIRValue, 8> innerParams;
  18777. BfExprEvaluator exprEvaluator(this);
  18778. if (!innerType->IsValuelessType())
  18779. {
  18780. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  18781. BfTypedValue innerVal(thisValue, innerType, true);
  18782. if (boxedType->IsBoxedStructPtr())
  18783. {
  18784. innerVal = LoadValue(innerVal);
  18785. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  18786. }
  18787. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  18788. }
  18789. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  18790. {
  18791. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  18792. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  18793. exprEvaluator.PushArg(localVal, innerParams);
  18794. }
  18795. if (!innerMethodInstance.mFunc)
  18796. {
  18797. BF_ASSERT(innerType->IsUnspecializedType());
  18798. }
  18799. else if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  18800. {
  18801. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  18802. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  18803. exprEvaluator.mReceivingValue = &returnType;
  18804. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  18805. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  18806. mBfIRBuilder->CreateRetVoid();
  18807. }
  18808. else
  18809. {
  18810. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  18811. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  18812. if (mCurMethodInstance->mReturnType->IsValueType())
  18813. retVal = LoadValue(retVal);
  18814. CreateReturn(retVal.mValue);
  18815. }
  18816. }
  18817. }
  18818. mCurMethodState->SetHadReturn(true);
  18819. mCurMethodState->mLeftBlockUncond = true;
  18820. }
  18821. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  18822. {
  18823. SetIllegalSrcPos();
  18824. mBfIRBuilder->ClearDebugLocation();
  18825. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  18826. auto thisVal = GetThis();
  18827. int prevSize = 0;
  18828. if (mContext->mBfObjectType != NULL)
  18829. {
  18830. prevSize = mContext->mBfObjectType->mInstSize;
  18831. PopulateType(mContext->mBfObjectType);
  18832. // If we have object extensions, clear out starting at the extension
  18833. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  18834. {
  18835. if (fieldInstance.GetFieldDef()->mDeclaringType->IsExtension())
  18836. {
  18837. prevSize = fieldInstance.mDataOffset;
  18838. break;
  18839. }
  18840. }
  18841. }
  18842. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  18843. int curSize = mCurTypeInstance->mInstSize;
  18844. if (curSize > prevSize)
  18845. {
  18846. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  18847. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  18848. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  18849. }
  18850. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  18851. {
  18852. auto useThis = mCurMethodState->mLocals[0]->mValue;
  18853. auto useThisType = mCurTypeInstance;
  18854. auto checkTypeInst = mCurTypeInstance;
  18855. while (checkTypeInst != NULL)
  18856. {
  18857. for (auto& fieldInstance : checkTypeInst->mFieldInstances)
  18858. {
  18859. auto fieldDef = fieldInstance.GetFieldDef();
  18860. if ((fieldDef == NULL) || (fieldDef->mIsStatic))
  18861. continue;
  18862. if (fieldInstance.IsAppendedObject())
  18863. {
  18864. if (checkTypeInst != useThisType)
  18865. {
  18866. useThis = mBfIRBuilder->CreateBitCast(useThis, mBfIRBuilder->MapType(checkTypeInst));
  18867. useThisType = checkTypeInst;
  18868. }
  18869. BfIRValue fieldAddr = mBfIRBuilder->CreateInBoundsGEP(useThis, 0, fieldInstance.mDataIdx);
  18870. auto int8PtrVal = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(int8PtrType));
  18871. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  18872. }
  18873. }
  18874. checkTypeInst = checkTypeInst->mBaseType;
  18875. }
  18876. }
  18877. skipUpdateSrcPos = true;
  18878. }
  18879. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  18880. {
  18881. EmitCtorBody(skipBody);
  18882. }
  18883. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  18884. {
  18885. EmitDtorBody();
  18886. skipBody = true;
  18887. }
  18888. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  18889. {
  18890. EmitIteratorBlock(skipBody);
  18891. }
  18892. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  18893. {
  18894. // We need to be able to mark deleted objects
  18895. mCurMethodState->mIgnoreObjectAccessCheck = true;
  18896. }
  18897. auto customAttributes = methodInstance->GetCustomAttributes();
  18898. if (customAttributes != NULL)
  18899. {
  18900. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  18901. mCurMethodState->mIgnoreObjectAccessCheck = true;
  18902. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  18903. mCurMethodState->mDisableChecks = true;
  18904. }
  18905. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  18906. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  18907. {
  18908. // We chain even non-default ctors to the default ctors
  18909. auto defaultCtor = methodInstance;
  18910. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  18911. CallChainedMethods(defaultCtor, false);
  18912. }
  18913. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  18914. if (!mCompiler->mHasRequiredTypes)
  18915. {
  18916. // Skip processing to avoid errors
  18917. }
  18918. else if (methodDef->mBody == NULL)
  18919. {
  18920. if (methodDeclaration != NULL)
  18921. {
  18922. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18923. {
  18924. if (operatorDeclaration->mIsConvOperator)
  18925. wantsRemoveBody = true;
  18926. }
  18927. }
  18928. bool isDllImport = false;
  18929. if ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic))
  18930. {
  18931. if (importStrNum != -1)
  18932. {
  18933. if (importKind == BfImportKind_Import_Static)
  18934. {
  18935. if (!mImportFileNames.Contains(importStrNum))
  18936. {
  18937. mImportFileNames.Add(importStrNum);
  18938. }
  18939. }
  18940. }
  18941. }
  18942. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  18943. {
  18944. CreateDllImportMethod();
  18945. }
  18946. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  18947. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  18948. {
  18949. if (mCurTypeInstance->mTypeDef->mIsFunction)
  18950. {
  18951. // Emit nothing
  18952. }
  18953. else
  18954. {
  18955. CreateDelegateInvokeMethod();
  18956. mCurMethodState->SetHadReturn(true);
  18957. mCurMethodState->mLeftBlockUncond = true;
  18958. }
  18959. }
  18960. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  18961. {
  18962. if (mCurTypeInstance->IsObject())
  18963. {
  18964. CreateDynamicCastMethod();
  18965. }
  18966. else
  18967. {
  18968. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  18969. mCurMethodState->mHadReturn = true;
  18970. }
  18971. }
  18972. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  18973. {
  18974. BfIRValue ret;
  18975. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  18976. {
  18977. // This can happen if we provide an invalid name
  18978. AssertErrorState();
  18979. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  18980. }
  18981. else
  18982. {
  18983. // Unfortunate DebugLoc shenanigans-
  18984. // 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,
  18985. // so we only set the loc on the CreateRet which gets inlined out
  18986. mBfIRBuilder->SaveDebugLocation();
  18987. mBfIRBuilder->ClearDebugLocation();
  18988. BfIRValue fromBool;
  18989. if ((!mCurTypeInstance->IsTypedPrimitive()) || (mCurTypeInstance->IsValuelessType()))
  18990. {
  18991. fromBool = GetDefaultValue(methodInstance->mReturnType);
  18992. }
  18993. else
  18994. {
  18995. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  18996. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  18997. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  18998. }
  18999. mBfIRBuilder->RestoreDebugLocation();
  19000. ret = mBfIRBuilder->CreateRet(fromBool);
  19001. //ExtendLocalLifetimes(0);
  19002. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19003. }
  19004. mCurMethodState->SetHadReturn(true);
  19005. mCurMethodState->mLeftBlockUncond = true;
  19006. }
  19007. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  19008. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  19009. {
  19010. BfIRValue ret;
  19011. // Unfortunate DebugLoc shenanigans-
  19012. // 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,
  19013. // so we only set the loc on the CreateRet which gets inlined out
  19014. mBfIRBuilder->SaveDebugLocation();
  19015. mBfIRBuilder->ClearDebugLocation();
  19016. BfIRValue fromBool;
  19017. mBfIRBuilder->RestoreDebugLocation();
  19018. if (!mCurTypeInstance->IsValuelessType())
  19019. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  19020. else
  19021. mBfIRBuilder->CreateRetVoid();
  19022. //ExtendLocalLifetimes(0);
  19023. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19024. mCurMethodState->SetHadReturn(true);
  19025. mCurMethodState->mLeftBlockUncond = true;
  19026. }
  19027. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  19028. {
  19029. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  19030. if (HasExecutedOutput())
  19031. {
  19032. EmitEnumToStringBody();
  19033. }
  19034. mBfIRBuilder->CreateRetVoid();
  19035. mCurMethodState->SetHadReturn(true);
  19036. mCurMethodState->mLeftBlockUncond = true;
  19037. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19038. }
  19039. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  19040. {
  19041. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  19042. if (HasExecutedOutput())
  19043. {
  19044. EmitTupleToStringBody();
  19045. }
  19046. mBfIRBuilder->CreateRetVoid();
  19047. mCurMethodState->SetHadReturn(true);
  19048. mCurMethodState->mLeftBlockUncond = true;
  19049. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19050. }
  19051. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  19052. {
  19053. CreateValueTypeEqualsMethod(false);
  19054. skipBody = true;
  19055. skipEndChecks = true;
  19056. }
  19057. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  19058. {
  19059. CreateValueTypeEqualsMethod(true);
  19060. skipBody = true;
  19061. skipEndChecks = true;
  19062. }
  19063. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef->GetDefinition() == mCompiler->mValueTypeTypeDef))
  19064. {
  19065. CreateValueTypeEqualsMethod(false);
  19066. skipBody = true;
  19067. skipEndChecks = true;
  19068. }
  19069. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (mCurTypeInstance->IsDelegate()))
  19070. {
  19071. CreateDelegateEqualsMethod();
  19072. skipBody = true;
  19073. skipEndChecks = true;
  19074. }
  19075. else
  19076. {
  19077. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  19078. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  19079. {
  19080. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  19081. Fail("Body expected", methodDef->mBody);
  19082. }
  19083. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  19084. {
  19085. if ((methodInstance->mReturnType->IsRef()) && (!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  19086. Fail("Auto-implemented ref property getters must declare 'mut'", methodInstance->mMethodDef->GetRefNode());
  19087. if (methodInstance->mReturnType->IsValuelessType())
  19088. {
  19089. mBfIRBuilder->CreateRetVoid();
  19090. }
  19091. else if (HasExecutedOutput())
  19092. {
  19093. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19094. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19095. BfFieldDef* fieldDef = NULL;
  19096. if (fieldInstance != NULL)
  19097. fieldDef = fieldInstance->GetFieldDef();
  19098. BfType* retType = methodInstance->mReturnType;
  19099. if (retType->IsRef())
  19100. retType = retType->GetUnderlyingType();
  19101. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  19102. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19103. {
  19104. BfTypedValue lookupValue;
  19105. if (fieldDef->IsNonConstStatic())
  19106. lookupValue = ReferenceStaticField(fieldInstance);
  19107. else if (mCurTypeInstance->IsObject())
  19108. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  19109. else
  19110. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  19111. if (methodInstance->mReturnType->IsRef())
  19112. {
  19113. if ((!lookupValue.IsAddr()) && (!lookupValue.mType->IsValuelessType()))
  19114. lookupValue = MakeAddressable(lookupValue);
  19115. }
  19116. else
  19117. lookupValue = LoadOrAggregateValue(lookupValue);
  19118. CreateReturn(lookupValue.mValue);
  19119. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19120. }
  19121. else
  19122. {
  19123. // This can happen if we have two properties with the same name but different types
  19124. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19125. EmitDefaultReturn();
  19126. }
  19127. }
  19128. else
  19129. {
  19130. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19131. EmitDefaultReturn();
  19132. }
  19133. mCurMethodState->SetHadReturn(true);
  19134. }
  19135. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  19136. {
  19137. if ((!methodDef->mIsMutating) && (!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  19138. {
  19139. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  19140. }
  19141. else if (!mCompiler->IsAutocomplete())
  19142. {
  19143. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19144. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19145. auto fieldDef = fieldInstance->GetFieldDef();
  19146. auto& lastParam = mCurMethodState->mLocals.back();
  19147. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  19148. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19149. {
  19150. BfIRValue lookupAddr;
  19151. if (fieldDef->IsNonConstStatic())
  19152. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  19153. else
  19154. {
  19155. auto thisValue = GetThis();
  19156. if (thisValue.IsSplat())
  19157. {
  19158. BFMODULE_FATAL(this, "Should not happen");
  19159. }
  19160. if (mCurTypeInstance->IsObject())
  19161. thisValue = LoadValue(thisValue);
  19162. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  19163. }
  19164. BfExprEvaluator exprEvaluator(this);
  19165. auto localVal = exprEvaluator.LoadLocal(lastParam);
  19166. localVal = LoadOrAggregateValue(localVal);
  19167. if (!localVal.mType->IsValuelessType())
  19168. mBfIRBuilder->CreateAlignedStore(localVal.mValue, lookupAddr, localVal.mType->mAlign);
  19169. }
  19170. else if (!fieldInstance->mResolvedType->IsValuelessType())
  19171. {
  19172. // This can happen if we have two properties with the same name but different types
  19173. AssertErrorState();
  19174. }
  19175. }
  19176. }
  19177. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  19178. {
  19179. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19180. {
  19181. if (HasCompiledOutput())
  19182. EmitGCMarkMembers();
  19183. }
  19184. else if (!mCurTypeInstance->IsObject())
  19185. {
  19186. }
  19187. }
  19188. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  19189. {
  19190. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19191. {
  19192. if (HasCompiledOutput())
  19193. EmitGCFindTLSMembers();
  19194. }
  19195. }
  19196. }
  19197. }
  19198. else if (!skipBody)
  19199. {
  19200. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  19201. bool wantsRetVal = true;
  19202. if ((mIsComptimeModule) && (methodDef->mMethodType != BfMethodType_CtorCalcAppend))
  19203. wantsRetVal = false;
  19204. else if (mCurMethodInstance->mReturnType->IsVar())
  19205. wantsRetVal = false;
  19206. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  19207. {
  19208. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  19209. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  19210. {
  19211. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  19212. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  19213. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst, mCurMethodInstance->mReturnType->mAlign);
  19214. mBfIRBuilder->ClearDebugLocation(storeInst);
  19215. mCurMethodState->mRetValAddr = allocaInst;
  19216. }
  19217. else if (wantsRetVal)
  19218. {
  19219. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  19220. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  19221. }
  19222. }
  19223. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19224. {
  19225. mBfIRBuilder->CreateAlignedStore(GetConstValue(0), mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19226. BfGetSymbolReferenceKind prevSymbolKind;
  19227. BfAutoComplete* prevAutoComplete;
  19228. if (mCompiler->mResolvePassData != NULL)
  19229. {
  19230. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  19231. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19232. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  19233. }
  19234. EmitCtorCalcAppend();
  19235. if (mCompiler->mResolvePassData != NULL)
  19236. {
  19237. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  19238. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  19239. }
  19240. }
  19241. else if (!isEmptyBodied)
  19242. {
  19243. if (!mCurMethodState->mIRExitBlock)
  19244. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  19245. bool isExpressionBody = false;
  19246. if (methodDeclaration != NULL)
  19247. {
  19248. if (methodDeclaration->mFatArrowToken != NULL)
  19249. isExpressionBody = true;
  19250. }
  19251. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  19252. {
  19253. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  19254. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  19255. isExpressionBody = true;
  19256. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  19257. {
  19258. isExpressionBody = true;
  19259. }
  19260. }
  19261. else
  19262. {
  19263. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  19264. {
  19265. if (!block->mChildArr.IsEmpty())
  19266. {
  19267. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  19268. {
  19269. if (exprStmt->mTrailingSemicolon == NULL)
  19270. isExpressionBody = true;
  19271. }
  19272. }
  19273. }
  19274. else
  19275. isExpressionBody = true;
  19276. }
  19277. DoCEEmit(methodInstance);
  19278. if (methodInstance->mCeCancelled)
  19279. mIgnoreErrors = true;
  19280. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  19281. {
  19282. while (fieldDtorBody != NULL)
  19283. {
  19284. VisitEmbeddedStatement(fieldDtorBody->mBody);
  19285. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  19286. }
  19287. }
  19288. else if (!isExpressionBody)
  19289. {
  19290. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  19291. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  19292. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  19293. VisitCodeBlock(bodyBlock);
  19294. }
  19295. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  19296. {
  19297. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  19298. // {
  19299. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  19300. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  19301. // }
  19302. auto expectingType = mCurMethodInstance->mReturnType;
  19303. // What was this error for?
  19304. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  19305. // {
  19306. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  19307. // }
  19308. BfEvalExprFlags exprEvalFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_IsExpressionBody);
  19309. if (expectingType->IsVoid())
  19310. {
  19311. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  19312. bool wasReturnGenericParam = false;
  19313. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  19314. {
  19315. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  19316. }
  19317. else
  19318. {
  19319. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  19320. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  19321. wasReturnGenericParam = true;
  19322. }
  19323. // If we the void return was from a generic specialization, allow us to return a void result,
  19324. // otherwise treat expression as though it must be a statement
  19325. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  19326. if (isStatement)
  19327. expectingType = NULL;
  19328. }
  19329. BfExprEvaluator exprEvaluator(this);
  19330. if (mCurMethodInstance->mMethodDef->mIsReadOnly)
  19331. exprEvaluator.mAllowReadOnlyReference = true;
  19332. UpdateSrcPos(expressionBody);
  19333. auto retVal = CreateValueFromExpression(exprEvaluator, expressionBody, expectingType, exprEvalFlags);
  19334. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  19335. {
  19336. mCurMethodState->mHadReturn = true;
  19337. if (!mCurMethodState->mLeftBlockUncond)
  19338. {
  19339. retVal = LoadOrAggregateValue(retVal);
  19340. EmitReturn(retVal);
  19341. }
  19342. }
  19343. }
  19344. }
  19345. }
  19346. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  19347. if (skipUpdateSrcPos)
  19348. {
  19349. // Skip
  19350. }
  19351. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19352. UpdateSrcPos(bodyBlock->mCloseBrace);
  19353. else if (methodDef->mBody != NULL)
  19354. UpdateSrcPos(methodDef->mBody);
  19355. else if (methodDeclaration != NULL)
  19356. UpdateSrcPos(methodDeclaration);
  19357. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  19358. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  19359. else
  19360. UseDefaultSrcPos();
  19361. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19362. {
  19363. if (mCurMethodState->mRetVal)
  19364. {
  19365. mCurMethodState->SetHadReturn(true);
  19366. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  19367. mBfIRBuilder->CreateRet(retVal);
  19368. }
  19369. else
  19370. AssertErrorState();
  19371. }
  19372. mCurMethodState->mHeadScope.mDone = true;
  19373. if (!mCurMethodState->mHadReturn)
  19374. {
  19375. // Clear off the stackallocs that have occurred after a scopeData break
  19376. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  19377. }
  19378. EmitDeferredCallProcessorInstances(&mCurMethodState->mHeadScope);
  19379. if (mCurMethodState->mIRExitBlock)
  19380. {
  19381. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  19382. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  19383. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  19384. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  19385. if ((!mCurMethodState->mDIRetVal) && (wantsDIData))
  19386. CreateDIRetVal();
  19387. }
  19388. for (auto localVar : mCurMethodState->mLocals)
  19389. {
  19390. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  19391. {
  19392. //
  19393. }
  19394. else if ((skipEndChecks) || (methodDef->mBody == NULL))
  19395. break;
  19396. LocalVariableDone(localVar, true);
  19397. }
  19398. if (mCurMethodState->mIRExitBlock)
  19399. {
  19400. if ((mCurMethodState->mRetVal) &&
  19401. ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() == -1)))
  19402. {
  19403. auto loadedVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19404. CreateReturn(loadedVal);
  19405. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19406. if (mCurMethodState->mDIRetVal)
  19407. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19408. }
  19409. else
  19410. {
  19411. // Have something on the last line to step onto
  19412. if (mHasFullDebugInfo)
  19413. {
  19414. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19415. UpdateSrcPos(bodyBlock->mCloseBrace);
  19416. EmitEnsureInstructionAt();
  19417. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19418. {
  19419. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19420. mBfIRBuilder->EnsureFunctionPatchable();
  19421. }
  19422. }
  19423. mBfIRBuilder->CreateRetVoid();
  19424. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19425. if (mCurMethodState->mDIRetVal)
  19426. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19427. }
  19428. }
  19429. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  19430. {
  19431. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  19432. {
  19433. if ((!mIsComptimeModule) && (irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19434. {
  19435. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19436. mBfIRBuilder->EnsureFunctionPatchable();
  19437. }
  19438. mBfIRBuilder->CreateRetVoid();
  19439. }
  19440. }
  19441. else
  19442. {
  19443. if (!mCurMethodState->mHadReturn)
  19444. {
  19445. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  19446. if (bodyBlock != NULL)
  19447. {
  19448. if (bodyBlock->mCloseBrace != NULL)
  19449. {
  19450. BfAstNode* target = bodyBlock->mCloseBrace;
  19451. if (!mCompiler->mHasRequiredTypes)
  19452. {
  19453. AddFailType(mCurTypeInstance);
  19454. mHadBuildError = true;
  19455. }
  19456. else
  19457. Fail("Method must return value", target);
  19458. }
  19459. else
  19460. {
  19461. // It's possible to not have a closing brace if the method ends in an EOF
  19462. AssertErrorState();
  19463. }
  19464. }
  19465. }
  19466. }
  19467. // Move 'init' into 'entry'
  19468. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  19469. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  19470. if (((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType())) &&
  19471. (!mIsComptimeModule))
  19472. {
  19473. // Don't keep instructions for unspecialized types
  19474. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19475. }
  19476. // Avoid linking any internal funcs that were just supposed to be comptime-accessible
  19477. /*if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  19478. wantsRemoveBody = true;*/
  19479. if ((hasExternSpecifier) && (!skipBody))
  19480. {
  19481. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  19482. // incase it gets called later by some hot-loaded coded
  19483. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()) && (mCurTypeInstance != mContext->mBfObjectType))
  19484. {
  19485. if (!mCurMethodInstance->mMethodDef->mName.StartsWith("Comptime_"))
  19486. CreateFakeCallerMethod(mangledName);
  19487. }
  19488. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19489. }
  19490. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  19491. {
  19492. // We only need the DLL stub when we may be hot swapping
  19493. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19494. }
  19495. else if (wantsRemoveBody)
  19496. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19497. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  19498. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  19499. // unspecialized types
  19500. if (((mCurTypeInstance->IsUnspecializedType()) && (!mIsComptimeModule)) ||
  19501. (mCurTypeInstance->IsInterface()))
  19502. {
  19503. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  19504. methodInstance->mIRFunction = BfIRFunction();
  19505. }
  19506. CheckAddFailType();
  19507. if (mHadBuildError)
  19508. prevHadBuildError.CancelRestore();
  19509. if (mHadBuildWarning)
  19510. prevHadWarning.CancelRestore();
  19511. if (!methodDef->mIsLocalMethod)
  19512. ProcessMethod_ProcessDeferredLocals();
  19513. prevIgnoreWrites.Restore();
  19514. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  19515. if (methodState.mHotDataReferenceBuilder != NULL)
  19516. {
  19517. AddHotDataReferences(&hotDataReferenceBuilder);
  19518. }
  19519. else
  19520. {
  19521. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  19522. {
  19523. // Remove the hot method data
  19524. auto hotMethod = methodInstance->mHotMethod;
  19525. auto prevMethod = hotMethod->mPrevVersion;
  19526. if (prevMethod != NULL)
  19527. {
  19528. // If there's a prev method then pull its data into the main HotMethod.
  19529. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  19530. // over to the main HotMethod definition to keep the HotMethod address
  19531. // invariant
  19532. for (auto ref : hotMethod->mReferences)
  19533. ref->Deref();
  19534. hotMethod->mReferences.Clear();
  19535. BF_ASSERT(prevMethod->mRefCount == 1);
  19536. hotMethod->mReferences = prevMethod->mReferences;
  19537. if (hotMethod->mSrcTypeVersion != NULL)
  19538. hotMethod->mSrcTypeVersion->Deref();
  19539. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  19540. prevMethod->mSrcTypeVersion = NULL;
  19541. prevMethod->mReferences.Clear();
  19542. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  19543. prevMethod->mPrevVersion = NULL;
  19544. prevMethod->Deref();
  19545. }
  19546. hotMethod->Deref();
  19547. methodInstance->mHotMethod = NULL;
  19548. }
  19549. }
  19550. }
  19551. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  19552. {
  19553. String name;
  19554. bool found = false;
  19555. auto checkMethodState = mCurMethodState;
  19556. while (checkMethodState != NULL)
  19557. {
  19558. if (checkMethodState->mClosureState == NULL)
  19559. break;
  19560. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  19561. {
  19562. found = true;
  19563. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  19564. break;
  19565. }
  19566. checkMethodState = checkMethodState->mPrevMethodState;
  19567. }
  19568. if (!found)
  19569. name += mCurMethodInstance->mMethodDef->mName;
  19570. int prevSepPos = (int)name.LastIndexOf('$');
  19571. if (prevSepPos != -1)
  19572. {
  19573. name.RemoveToEnd(prevSepPos);
  19574. }
  19575. name += "@";
  19576. name += baseName;
  19577. HashContext hashCtx;
  19578. if (anchorNode != NULL)
  19579. {
  19580. hashCtx.Mixin(anchorNode->GetStartCharId());
  19581. }
  19582. //
  19583. {
  19584. auto checkMethodState = declMethodState;
  19585. auto checkMixinState = declMixinState;
  19586. while (checkMethodState != NULL)
  19587. {
  19588. if (checkMixinState != NULL)
  19589. {
  19590. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  19591. }
  19592. checkMethodState = checkMethodState->mPrevMethodState;
  19593. if (checkMethodState != NULL)
  19594. checkMixinState = checkMethodState->mMixinState;
  19595. }
  19596. }
  19597. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19598. if ((rootMethodState != NULL) && (rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19599. {
  19600. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  19601. {
  19602. StringT<512> genericTypeName;
  19603. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  19604. hashCtx.MixinStr(genericTypeName);
  19605. }
  19606. }
  19607. uint64 hashVal = hashCtx.Finish64();
  19608. name += "$";
  19609. name += BfTypeUtils::HashEncode64(hashVal);
  19610. return name;
  19611. }
  19612. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  19613. {
  19614. if (localMethod->mMethodDef != NULL)
  19615. return localMethod->mMethodDef;
  19616. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19617. auto declMethodState = localMethod->mDeclMethodState;
  19618. auto declMixinState = localMethod->mDeclMixinState;
  19619. auto typeInst = mCurTypeInstance;
  19620. BfAstNode* body = NULL;
  19621. BfAstNode* anchorNode = NULL;
  19622. auto _AllocDirectTypeRef = [&](BfType* type)
  19623. {
  19624. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  19625. directTypeRef->Init(type);
  19626. return directTypeRef;
  19627. };
  19628. auto methodDeclaration = localMethod->mMethodDeclaration;
  19629. if (methodDeclaration != NULL)
  19630. {
  19631. body = methodDeclaration->mBody;
  19632. anchorNode = methodDeclaration->mOpenParen;
  19633. }
  19634. else
  19635. {
  19636. body = localMethod->mLambdaBindExpr->mBody;
  19637. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  19638. }
  19639. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  19640. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  19641. BfMethodDef* methodDef;
  19642. BfMethodDef* outerMethodDef = NULL;
  19643. if (localMethod->mOuterLocalMethod != NULL)
  19644. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  19645. else if (rootMethodState->mMethodInstance != NULL)
  19646. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  19647. if (methodDeclaration != NULL)
  19648. {
  19649. BfDefBuilder defBuilder(mCompiler->mSystem);
  19650. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  19651. defBuilder.mPassInstance = mCompiler->mPassInstance;
  19652. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  19653. defBuilder.mCurDeclaringTypeDef = defBuilder.mCurTypeDef;
  19654. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  19655. }
  19656. else
  19657. {
  19658. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  19659. methodDef = new BfMethodDef();
  19660. methodDef->mName = localMethod->mMethodName;
  19661. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  19662. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  19663. methodDef->mBody = body;
  19664. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  19665. {
  19666. auto paramType = invokeMethod->GetParamType(paramIdx);
  19667. String paramName;
  19668. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  19669. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  19670. else
  19671. paramName = invokeMethod->GetParamName(paramIdx);
  19672. auto paramDef = new BfParameterDef();
  19673. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  19674. paramDef->mName = paramName;
  19675. methodDef->mParams.Add(paramDef);
  19676. }
  19677. if (outerMethodDef != NULL)
  19678. {
  19679. for (auto genericParam : outerMethodDef->mGenericParams)
  19680. {
  19681. auto* copiedGenericParamDef = new BfGenericParamDef();
  19682. *copiedGenericParamDef = *genericParam;
  19683. methodDef->mGenericParams.Add(copiedGenericParamDef);
  19684. }
  19685. }
  19686. }
  19687. methodDef->mIdx = ~methodLocalIdx;
  19688. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  19689. methodDef->mName = localMethod->mExpectedFullName;
  19690. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  19691. //
  19692. // if (!localMethod->mExpectedFullName.IsEmpty())
  19693. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  19694. methodDef->mIsStatic = true;
  19695. methodDef->mIsLocalMethod = true;
  19696. methodDef->mIsVirtual = false;
  19697. localMethod->mMethodDef = methodDef;
  19698. auto methodInstanceGroup = new BfMethodInstanceGroup();
  19699. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  19700. methodInstanceGroup->mMethodIdx = -1;
  19701. methodInstanceGroup->mOwner = mCurTypeInstance;
  19702. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  19703. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  19704. {
  19705. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  19706. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  19707. }
  19708. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  19709. {
  19710. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  19711. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19712. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  19713. {
  19714. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  19715. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  19716. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  19717. autoComplete->mDefType = typeInst->mTypeDef;
  19718. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  19719. autoComplete->mReplaceLocalId = methodLocalIdx;
  19720. }
  19721. }
  19722. return localMethod->mMethodDef;
  19723. }
  19724. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  19725. {
  19726. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  19727. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  19728. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19729. auto declMethodState = localMethod->mDeclMethodState;
  19730. auto declMixinState = localMethod->mDeclMixinState;
  19731. auto callerMethodState = mCurMethodState;
  19732. auto typeInst = mCurTypeInstance;
  19733. if (mCurMethodState->mMixinState != NULL)
  19734. {
  19735. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  19736. }
  19737. auto methodDef = GetLocalMethodDef(localMethod);
  19738. BfAstNode* body = NULL;
  19739. auto methodDeclaration = localMethod->mMethodDeclaration;
  19740. if (methodDeclaration != NULL)
  19741. {
  19742. body = methodDeclaration->mBody;
  19743. }
  19744. else
  19745. {
  19746. body = localMethod->mLambdaBindExpr->mBody;
  19747. }
  19748. bool hadConcreteInterfaceGenericArgument = false;
  19749. BfTypeVector sanitizedMethodGenericArguments;
  19750. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  19751. // version of this method for this pass through the outermost method
  19752. int dependentGenericStartIdx = 0;
  19753. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19754. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  19755. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  19756. if (methodGenericArguments.size() == 0)
  19757. {
  19758. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19759. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  19760. }
  19761. else
  19762. {
  19763. int genericArgIdx = 0;
  19764. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  19765. // {
  19766. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  19767. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  19768. // }
  19769. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  19770. {
  19771. auto genericArgType = methodGenericArguments[genericArgIdx];
  19772. BF_ASSERT(!genericArgType->IsRef());
  19773. if (genericArgType->IsConcreteInterfaceType())
  19774. {
  19775. hadConcreteInterfaceGenericArgument = true;
  19776. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  19777. genericArgType = concreteInterfaceType->mInterface;
  19778. }
  19779. sanitizedMethodGenericArguments.push_back(genericArgType);
  19780. }
  19781. }
  19782. bool wantPrematureMethodInstance = false;
  19783. if (!force)
  19784. {
  19785. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  19786. }
  19787. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  19788. bool isDefaultPass = true;
  19789. BfTypeVector lookupMethodGenericArguments;
  19790. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  19791. {
  19792. auto genericArgType = methodGenericArguments[genericArgIdx];
  19793. BF_ASSERT(!genericArgType->IsRef());
  19794. lookupMethodGenericArguments.Add(genericArgType);
  19795. if (genericArgType->IsGenericParam())
  19796. {
  19797. auto genericParam = (BfGenericParamType*)genericArgType;
  19798. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  19799. isDefaultPass = false;
  19800. }
  19801. else
  19802. {
  19803. isDefaultPass = false;
  19804. }
  19805. }
  19806. bool hadExistingMethodInstance = false;
  19807. if (methodInstance != NULL)
  19808. {
  19809. hadExistingMethodInstance = true;
  19810. }
  19811. else
  19812. {
  19813. if (isDefaultPass)
  19814. {
  19815. methodInstance = methodInstGroup->mDefault;
  19816. if (methodInstance != NULL)
  19817. {
  19818. hadExistingMethodInstance = true;
  19819. }
  19820. else
  19821. {
  19822. methodInstance = new BfMethodInstance();
  19823. methodInstGroup->mDefault = methodInstance;
  19824. }
  19825. }
  19826. else
  19827. {
  19828. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  19829. if (methodInstGroup->mMethodSpecializationMap == NULL)
  19830. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  19831. BfMethodInstance** methodInstancePtr = NULL;
  19832. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  19833. {
  19834. methodInstance = *methodInstancePtr;
  19835. hadExistingMethodInstance = true;
  19836. }
  19837. else
  19838. {
  19839. methodInstance = new BfMethodInstance();
  19840. *methodInstancePtr = methodInstance;
  19841. }
  19842. }
  19843. }
  19844. if (hadExistingMethodInstance)
  19845. {
  19846. if ((!methodInstance->mDisallowCalling) ||
  19847. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  19848. return BfModuleMethodInstance(methodInstance);
  19849. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  19850. }
  19851. else
  19852. {
  19853. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  19854. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  19855. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  19856. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  19857. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  19858. methodInstance->mMethodDef = methodDef;
  19859. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  19860. if (hadConcreteInterfaceGenericArgument)
  19861. methodInstance->mIgnoreBody = true;
  19862. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  19863. for (auto genericArg : sanitizedMethodGenericArguments)
  19864. {
  19865. if (genericArg->IsPrimitiveType())
  19866. genericArg = GetWrappedStructType(genericArg);
  19867. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  19868. }
  19869. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  19870. {
  19871. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  19872. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  19873. }
  19874. SetupMethodIdHash(methodInstance);
  19875. }
  19876. auto _SetupMethodInstance = [&]()
  19877. {
  19878. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  19879. // Generic constraints
  19880. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  19881. {
  19882. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  19883. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  19884. }
  19885. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  19886. {
  19887. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  19888. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  19889. }
  19890. };
  19891. //////////////////////////////////////////////////////////////////////////
  19892. auto _VisitLambdaBody = [&]()
  19893. {
  19894. if (localMethod->mDeclOnly)
  19895. return;
  19896. if (mCompiler->mCanceling)
  19897. return;
  19898. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  19899. {
  19900. VisitCodeBlock(blockBody);
  19901. }
  19902. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  19903. {
  19904. BfType* expectType = NULL;
  19905. if (!methodInstance->mReturnType->IsVoid())
  19906. expectType = methodInstance->mReturnType;
  19907. CreateValueFromExpression(bodyExpr, expectType, BfEvalExprFlags_AllowRefExpr);
  19908. }
  19909. };
  19910. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  19911. {
  19912. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  19913. auto result = ResolveTypeRef(typeRef);
  19914. if (result == NULL)
  19915. result = mContext->mBfObjectType;
  19916. return result;
  19917. };
  19918. BfTypeInstance* outerClosure = NULL;
  19919. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  19920. outerClosure = declMethodState->mClosureState->mClosureType;
  19921. BfMethodState methodState;
  19922. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  19923. BfIRFunctionType funcType;
  19924. auto voidType = GetPrimitiveType(BfTypeCode_None);
  19925. SizedArray<BfIRType, 0> paramTypes;
  19926. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  19927. mBfIRBuilder->SaveDebugLocation();
  19928. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  19929. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  19930. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  19931. BfDeferredLocalAssignData deferredLocalAssignData;
  19932. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  19933. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  19934. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  19935. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  19936. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  19937. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  19938. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  19939. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  19940. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  19941. methodState.mIRFunction = declMethodState->mIRFunction;
  19942. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  19943. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  19944. {
  19945. methodState.mCurScope->mAstBlock = blockBody;
  19946. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  19947. }
  19948. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  19949. BfClosureState closureState;
  19950. if (methodDef->mMethodType == BfMethodType_Mixin)
  19951. {
  19952. if (declMethodState != NULL)
  19953. {
  19954. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  19955. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  19956. else if (declMethodState->mMethodInstance != NULL)
  19957. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  19958. }
  19959. }
  19960. if (closureState.mReturnType == NULL)
  19961. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  19962. closureState.mCapturing = true;
  19963. closureState.mLocalMethod = localMethod;
  19964. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  19965. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  19966. methodState.mClosureState = &closureState;
  19967. closureState.mClosureType = outerClosure;
  19968. int outerLocalsCount = (int)methodState.mLocals.size();
  19969. if (!hadExistingMethodInstance)
  19970. {
  19971. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  19972. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  19973. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  19974. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  19975. auto declareModule = this;
  19976. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  19977. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  19978. BF_ASSERT(declareModule != NULL);
  19979. methodInstance->mDeclModule = declareModule;
  19980. _SetupMethodInstance();
  19981. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  19982. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  19983. }
  19984. if (wantPrematureMethodInstance)
  19985. {
  19986. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  19987. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  19988. // its true method instance
  19989. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  19990. //BF_ASSERT(moduleMethodInstance);
  19991. return BfModuleMethodInstance(methodInstance);
  19992. }
  19993. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  19994. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  19995. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  19996. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  19997. closureState.mClosureMethodDef = methodDef;
  19998. bool wantsVisitBody = true;
  19999. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  20000. wantsVisitBody = false;
  20001. if (methodInstance->IsOrInUnspecializedVariation())
  20002. wantsVisitBody = false;
  20003. bool allowCapture = (methodDeclaration == NULL) || (methodDeclaration->mStaticSpecifier == NULL);
  20004. if (wantsVisitBody)
  20005. {
  20006. BP_ZONE("VisitLambdaBody");
  20007. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  20008. // this capture stage for each of those times
  20009. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  20010. /*
  20011. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  20012. // that will not occur during the actual lambda method generation, for example: returning a value
  20013. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  20014. // our AST nodes will still be visited
  20015. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  20016. */
  20017. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20018. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  20019. mBfIRBuilder->SaveDebugLocation();
  20020. closureState.mCaptureVisitingBody = true;
  20021. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  20022. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  20023. methodState.mMethodInstance = methodInstance;
  20024. NewScopeState();
  20025. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  20026. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  20027. {
  20028. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  20029. for (auto localDef : methodState.mLocals)
  20030. {
  20031. if (localDef->mResolvedType->IsVar())
  20032. continue;
  20033. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  20034. }
  20035. }
  20036. // Keep outs from being marked as assigned
  20037. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20038. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  20039. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  20040. auto prevDLA = rootMethodState->mDeferredLocalAssignData;
  20041. while ((prevDLA != NULL) && (prevDLA->mIsChained))
  20042. prevDLA = prevDLA->mChainedAssignData;
  20043. if (prevDLA != NULL)
  20044. {
  20045. deferredLocalAssignData.mAssignedLocals = prevDLA->mAssignedLocals;
  20046. deferredLocalAssignData.mLeftBlockUncond = prevDLA->mLeftBlockUncond;
  20047. }
  20048. SetAndRestoreValue<BfDeferredLocalAssignData*> sarDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  20049. if (!mIgnoreErrors)
  20050. localMethod->mDidBodyErrorPass = true;
  20051. _VisitLambdaBody();
  20052. RestoreScopeState();
  20053. closureState.mCaptureVisitingBody = false;
  20054. mBfIRBuilder->RestoreDebugLocation();
  20055. }
  20056. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  20057. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  20058. {
  20059. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  20060. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  20061. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  20062. }
  20063. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  20064. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  20065. closureState.mClosureMethodDef = NULL;
  20066. for (auto methodInstance : closureState.mLocalMethodRefs)
  20067. {
  20068. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  20069. }
  20070. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  20071. prevIgnoreWrites.Restore();
  20072. std::multiset<BfClosureCapturedEntry> capturedEntries;
  20073. //
  20074. {
  20075. auto varMethodState = declMethodState;
  20076. while (varMethodState != NULL)
  20077. {
  20078. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  20079. {
  20080. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  20081. methodDef->mIsStatic = false;
  20082. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20083. methodDef->mIsMutating = true;
  20084. }
  20085. bool copyOuterCaptures = false;
  20086. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  20087. {
  20088. auto localVar = varMethodState->mLocals[localIdx];
  20089. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20090. {
  20091. if (!allowCapture)
  20092. {
  20093. if ((!localVar->mIsStatic) && (!localVar->mConstValue))
  20094. continue;
  20095. }
  20096. if (localVar->mIsThis)
  20097. {
  20098. // We can only set mutating if our owning type is mutating
  20099. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  20100. {
  20101. if (typeInst->IsValueType())
  20102. {
  20103. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20104. methodDef->mIsMutating = true;
  20105. }
  20106. }
  20107. methodDef->mIsStatic = false;
  20108. continue;
  20109. }
  20110. if ((localVar->mIsThis) && (outerClosure != NULL))
  20111. {
  20112. continue;
  20113. }
  20114. if ((localVar->mConstValue) || (localVar->mIsStatic) || (localVar->mResolvedType->IsValuelessType()))
  20115. {
  20116. closureState.mConstLocals.push_back(*localVar);
  20117. continue;
  20118. }
  20119. BfClosureCapturedEntry capturedEntry;
  20120. auto capturedType = localVar->mResolvedType;
  20121. bool captureByRef = false;
  20122. if (!capturedType->IsRef())
  20123. {
  20124. if (localVar->mIsThis)
  20125. {
  20126. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  20127. captureByRef = true;
  20128. }
  20129. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20130. captureByRef = true;
  20131. }
  20132. else
  20133. {
  20134. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  20135. {
  20136. capturedType = ((BfRefType*)capturedType)->mElementType;
  20137. }
  20138. }
  20139. if (captureByRef)
  20140. {
  20141. //capturedEntry.mIsByReference = true;
  20142. capturedType = CreateRefType(capturedType);
  20143. }
  20144. else
  20145. {
  20146. //capturedEntry.mIsByReference = false;
  20147. }
  20148. capturedEntry.mNameNode = localVar->mNameNode;
  20149. capturedEntry.mType = capturedType;
  20150. capturedEntry.mName = localVar->mName;
  20151. //capturedEntry.mLocalVarDef = localVar;
  20152. capturedEntries.insert(capturedEntry);
  20153. }
  20154. }
  20155. varMethodState = varMethodState->mPrevMethodState;
  20156. if ((varMethodState == NULL) ||
  20157. (varMethodState->mMixinState != NULL) ||
  20158. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  20159. break;
  20160. }
  20161. }
  20162. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  20163. {
  20164. auto fieldDef = copyField->GetFieldDef();
  20165. BfClosureCapturedEntry capturedEntry;
  20166. capturedEntry.mName = copyField->GetFieldDef()->mName;
  20167. capturedEntry.mType = copyField->mResolvedType;
  20168. if (capturedEntry.mType->IsRef())
  20169. {
  20170. // Keep by ref
  20171. }
  20172. else if (!fieldDef->mIsReadOnly)
  20173. {
  20174. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  20175. }
  20176. capturedEntries.insert(capturedEntry);
  20177. }
  20178. int captureIdx = 0;
  20179. for (auto& capturedEntry : capturedEntries)
  20180. {
  20181. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  20182. }
  20183. /*if (isDefaultPass)
  20184. {
  20185. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  20186. int captureIdx = 0;
  20187. for (auto& capturedEntry : capturedEntries)
  20188. {
  20189. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  20190. BfParameterDef* paramDef = new BfParameterDef();
  20191. paramDef->mName = capturedEntry.mName;
  20192. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  20193. directTypeRef->mType = capturedEntry.mType;
  20194. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  20195. paramDef->mTypeRef = directTypeRef;
  20196. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  20197. methodDef->mParams.Insert(captureIdx, paramDef);
  20198. captureIdx++;
  20199. }
  20200. }
  20201. else
  20202. {
  20203. auto defaultMethodInstance = methodInstGroup->mDefault;
  20204. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  20205. }*/
  20206. methodState.Reset();
  20207. closureState.mCapturing = false;
  20208. //////////////////////////////////////////////////////////////////////////
  20209. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  20210. if (methodInstance->mReturnType != NULL)
  20211. {
  20212. BF_ASSERT(methodInstance->mDisallowCalling);
  20213. // We did a premature declaration (without captures)
  20214. methodInstance->UndoDeclaration();
  20215. methodInstance->mDisallowCalling = false;
  20216. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  20217. }
  20218. auto declareModule = this;
  20219. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  20220. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  20221. BF_ASSERT(declareModule != NULL);
  20222. methodInstance->mDeclModule = declareModule;
  20223. _SetupMethodInstance();
  20224. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  20225. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  20226. closureState.mReturnType = methodInstance->mReturnType;
  20227. mCompiler->mStats.mMethodsQueued++;
  20228. mCompiler->UpdateCompletion();
  20229. declareModule->mIncompleteMethodCount++;
  20230. mCompiler->mStats.mMethodsProcessed++;
  20231. if (!methodInstance->mIsReified)
  20232. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  20233. auto deferMethodState = rootMethodState;
  20234. // 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)
  20235. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  20236. (methodDef->mMethodType != BfMethodType_Mixin) &&
  20237. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)) &&
  20238. (!mCompiler->IsDataResolvePass()))
  20239. {
  20240. BP_ZONE("BfDeferredLocalMethod:create");
  20241. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  20242. deferredLocalMethod->mLocalMethod = localMethod;
  20243. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  20244. deferredLocalMethod->mMethodInstance = methodInstance;
  20245. auto checkMethodState = declMethodState;
  20246. while (checkMethodState != NULL)
  20247. {
  20248. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  20249. {
  20250. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  20251. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20252. }
  20253. if (checkMethodState->mMixinState != NULL)
  20254. {
  20255. BfMixinRecord mixinRecord;
  20256. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  20257. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20258. }
  20259. checkMethodState = checkMethodState->mPrevMethodState;
  20260. }
  20261. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  20262. }
  20263. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  20264. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  20265. mBfIRBuilder->RestoreDebugLocation();
  20266. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  20267. {
  20268. auto checkMethodState = mCurMethodState;
  20269. while (checkMethodState != NULL)
  20270. {
  20271. BfLocalMethod* nextLocalMethod = NULL;
  20272. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  20273. {
  20274. while (nextLocalMethod != NULL)
  20275. {
  20276. auto checkLocalMethod = nextLocalMethod;
  20277. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  20278. if (checkLocalMethod == localMethod)
  20279. continue;
  20280. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  20281. continue;
  20282. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  20283. if (checkMethodInstance == NULL)
  20284. continue; // Not generated yet
  20285. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  20286. {
  20287. String error = "Method already declared with the same parameter types";
  20288. auto bfError = Fail(error, methodInstance->mMethodDef->GetRefNode(), true);
  20289. if ((bfError != NULL) && (methodInstance->mMethodDef->GetRefNode() != checkMethodInstance->mMethodDef->GetRefNode()))
  20290. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  20291. }
  20292. }
  20293. }
  20294. checkMethodState = checkMethodState->mPrevMethodState;
  20295. }
  20296. }
  20297. return BfModuleMethodInstance(methodInstance);
  20298. }
  20299. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  20300. {
  20301. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  20302. return 0;
  20303. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20304. int rootMethodGenericParamCount = 0;
  20305. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  20306. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  20307. if (mCurMethodInstance == NULL)
  20308. return rootMethodGenericParamCount;
  20309. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  20310. return rootMethodGenericParamCount;
  20311. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  20312. if (callerLocalMethod == NULL)
  20313. return rootMethodGenericParamCount;
  20314. BfLocalMethod* calledLocalMethod = NULL;
  20315. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  20316. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  20317. {
  20318. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  20319. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  20320. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  20321. }
  20322. return rootMethodGenericParamCount;
  20323. }
  20324. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  20325. {
  20326. auto methodDef = methodInstance->mMethodDef;
  20327. auto customAttributes = methodInstance->GetCustomAttributes();
  20328. if (customAttributes != NULL)
  20329. return;
  20330. auto methodDeclaration = methodDef->GetMethodDeclaration();
  20331. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  20332. auto typeInstance = methodInstance->GetOwner();
  20333. if (typeInstance->IsInstanceOf(mCompiler->mValueTypeTypeDef))
  20334. return;
  20335. BfTypeState typeState(typeInstance);
  20336. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20337. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  20338. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20339. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  20340. BfAttributeDirective* attributeDirective = NULL;
  20341. if (methodDeclaration != NULL)
  20342. attributeDirective = methodDeclaration->mAttributes;
  20343. else if (propertyMethodDeclaration != NULL)
  20344. {
  20345. attributeDirective = propertyMethodDeclaration->mAttributes;
  20346. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  20347. {
  20348. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  20349. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  20350. }
  20351. }
  20352. if (attributeDirective != NULL)
  20353. {
  20354. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20355. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20356. if ((methodInstance == methodInstance->mMethodInstanceGroup->mDefault) && (methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes != NULL))
  20357. {
  20358. // Take over previously-generated custom attributes
  20359. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes;
  20360. methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes = NULL;
  20361. }
  20362. else
  20363. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  20364. }
  20365. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mPropertyDeclaration->mAttributes != NULL) && ((attrTarget & BfAttributeTargets_Property) == 0))
  20366. {
  20367. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes != NULL)
  20368. {
  20369. GetCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20370. }
  20371. else
  20372. {
  20373. methodInstance->GetMethodInfoEx()->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20374. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20375. }
  20376. }
  20377. if (methodDeclaration != NULL)
  20378. {
  20379. if (auto inlineTypeRef = BfNodeDynCast<BfInlineTypeReference>(methodDeclaration->mReturnType))
  20380. {
  20381. if (inlineTypeRef->mTypeDeclaration->mAttributes != NULL)
  20382. {
  20383. // Apply multiuse attributes from anonymous return type
  20384. auto returnType = ResolveTypeRef(inlineTypeRef);
  20385. if ((returnType != NULL) && (returnType->ToTypeInstance()))
  20386. {
  20387. auto returnTypeInst = returnType->ToTypeInstance();
  20388. if ((returnTypeInst->IsAnonymous()) && (returnTypeInst->mCustomAttributes != NULL))
  20389. {
  20390. bool hasPendingAttributes = false;
  20391. for (const auto& customAttribute : returnTypeInst->mCustomAttributes->mAttributes)
  20392. {
  20393. if (customAttribute.mAwaitingValidation)
  20394. {
  20395. hasPendingAttributes = true;
  20396. break;
  20397. }
  20398. }
  20399. if (hasPendingAttributes)
  20400. {
  20401. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20402. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20403. if (methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes == NULL)
  20404. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = new BfCustomAttributes();
  20405. for (const auto& customAttribute : returnTypeInst->mCustomAttributes->mAttributes)
  20406. {
  20407. if (!customAttribute.mAwaitingValidation)
  20408. continue;
  20409. BfCustomAttribute copiedCustomAttribute = customAttribute;
  20410. copiedCustomAttribute.mIsMultiUse = false;
  20411. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes.Add(copiedCustomAttribute);
  20412. }
  20413. ValidateCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, attrTarget);
  20414. }
  20415. }
  20416. }
  20417. }
  20418. }
  20419. }
  20420. customAttributes = methodInstance->GetCustomAttributes();
  20421. if (customAttributes == NULL)
  20422. {
  20423. auto owner = methodInstance->GetOwner();
  20424. if ((owner->IsDelegate()) || (owner->IsFunction()))
  20425. customAttributes = owner->mCustomAttributes;
  20426. }
  20427. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  20428. if (customAttributes != NULL)
  20429. {
  20430. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  20431. if (linkNameAttr != NULL)
  20432. {
  20433. if (linkNameAttr->mCtorArgs.size() == 1)
  20434. {
  20435. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  20436. if (constant != NULL)
  20437. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  20438. }
  20439. }
  20440. if (methodDef->mHasComptime)
  20441. methodInstance->mComptimeFlags = BfComptimeFlag_Comptime;
  20442. auto comptimeAttr = customAttributes->Get(mCompiler->mComptimeAttributeTypeDef);
  20443. if (comptimeAttr != NULL)
  20444. {
  20445. for (auto setProp : comptimeAttr->mSetProperties)
  20446. {
  20447. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  20448. if (propertyDef->mName == "OnlyFromComptime")
  20449. {
  20450. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  20451. if ((constant != NULL) && (constant->mBool))
  20452. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_OnlyFromComptime);
  20453. }
  20454. else if (propertyDef->mName == "ConstEval")
  20455. {
  20456. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  20457. if ((constant != NULL) && (constant->mBool))
  20458. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_ConstEval);
  20459. }
  20460. }
  20461. }
  20462. }
  20463. auto delegateInfo = typeInstance->GetDelegateInfo();
  20464. if ((delegateInfo != NULL) && (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) && (methodInstance->mMethodDef->mName == "Invoke"))
  20465. methodInstance->mCallingConvention = delegateInfo->mCallingConvention;
  20466. }
  20467. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  20468. {
  20469. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  20470. {
  20471. // Don't create a func
  20472. return;
  20473. }
  20474. auto typeInstance = methodInstance->GetOwner();
  20475. auto methodDef = methodInstance->mMethodDef;
  20476. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  20477. if (isTemporaryFunc)
  20478. {
  20479. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  20480. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  20481. mangledName = "autocomplete_tmp";
  20482. }
  20483. if (!mBfIRBuilder->mIgnoreWrites)
  20484. {
  20485. BfIRFunction prevFunc;
  20486. // Remove old version (if we have one)
  20487. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  20488. if (prevFunc)
  20489. {
  20490. if ((methodDef->mIsOverride) && (mCurTypeInstance->mTypeDef->mIsCombinedPartial))
  20491. {
  20492. bool takeover = false;
  20493. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  20494. BfMethodDef* nextMethod = NULL;
  20495. BfMemberSetEntry* entry = NULL;
  20496. if (mCurTypeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  20497. nextMethod = (BfMethodDef*)entry->mMemberDef;
  20498. while (nextMethod != NULL)
  20499. {
  20500. auto checkMethod = nextMethod;
  20501. nextMethod = nextMethod->mNextWithSameName;
  20502. if (checkMethod == methodDef)
  20503. continue;
  20504. if (checkMethod->mIsOverride)
  20505. {
  20506. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20507. if (checkMethodInstance == NULL)
  20508. continue;
  20509. if ((checkMethodInstance->mIRFunction == prevFunc) &&
  20510. (checkMethodInstance->mMethodDef->mMethodDeclaration != NULL) &&
  20511. (checkMethodInstance->mVirtualTableIdx < 0))
  20512. {
  20513. BfAstNode* refNode = methodDef->GetRefNode();
  20514. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  20515. refNode = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  20516. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  20517. refNode = methodDeclaration->mVirtualSpecifier;
  20518. auto error = Fail(StrFormat("Conflicting extension override method '%s'", MethodToString(mCurMethodInstance).c_str()), refNode);
  20519. if (error != NULL)
  20520. mCompiler->mPassInstance->MoreInfo("See previous override", checkMethod->GetRefNode());
  20521. takeover = false;
  20522. break;
  20523. }
  20524. }
  20525. if (!checkMethod->mIsExtern)
  20526. continue;
  20527. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20528. if (checkMethodInstance == NULL)
  20529. continue;
  20530. if (!CompareMethodSignatures(checkMethodInstance, mCurMethodInstance))
  20531. continue;
  20532. // Take over function
  20533. takeover = true;
  20534. }
  20535. if (takeover)
  20536. mCurMethodInstance->mIRFunction = prevFunc;
  20537. if (!mCurMethodInstance->mIRFunction)
  20538. {
  20539. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  20540. if (!mIsComptimeModule)
  20541. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  20542. }
  20543. }
  20544. else if (methodDef->mIsExtern)
  20545. {
  20546. // Allow this
  20547. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  20548. }
  20549. else if (typeInstance->IsIRFuncUsed(prevFunc))
  20550. {
  20551. // We can have a collision of names when we have generic methods that differ only in
  20552. // their constraints, but they should only collide in their unspecialized form
  20553. // since only one will be chosen for a given concrete type
  20554. if (!mIsComptimeModule)
  20555. mCurMethodInstance->mMangleWithIdx = true;
  20556. mangledName.Clear();
  20557. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  20558. BfLogSysM("Function collision forced mangleWithIdx for %p: %d GenericArgs: %d Unspecialized: %d\n", methodInstance, prevFunc.mId, methodInstance->GetNumGenericArguments(), methodInstance->mIsUnspecialized);
  20559. }
  20560. else
  20561. {
  20562. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  20563. if (!mIsComptimeModule)
  20564. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  20565. }
  20566. }
  20567. }
  20568. if (typeInstance != mContext->mBfObjectType)
  20569. {
  20570. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  20571. GetMethodCustomAttributes(methodInstance);
  20572. }
  20573. // if (prevFunc)
  20574. // {
  20575. // if (methodDef->mIsExtern)
  20576. // {
  20577. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  20578. // methodInstance->mIRFunction = prevFunc;
  20579. // }
  20580. // else
  20581. // {
  20582. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  20583. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  20584. // {
  20585. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  20586. // BfLogSysM("Ignoring function name collision\n");
  20587. // }
  20588. // else
  20589. // {
  20590. // if (methodDef->mMethodDeclaration == NULL)
  20591. // {
  20592. // AssertErrorState();
  20593. // }
  20594. // else
  20595. // {
  20596. // BF_ASSERT(mIsSpecialModule);
  20597. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  20598. // {
  20599. // // We shouldn't have name collisions on the first run!
  20600. // AssertErrorState();
  20601. // }
  20602. // }
  20603. // }
  20604. // BfLogSysM("Before erase\n");
  20605. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  20606. // }
  20607. // }
  20608. bool isIntrinsic = false;
  20609. if (!methodInstance->mIRFunction)
  20610. {
  20611. BfIRFunction func;
  20612. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType() || (mIsComptimeModule)) &&
  20613. (!methodDef->IsEmptyPartial())) && (funcType);
  20614. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  20615. {
  20616. if (!mIsReified)
  20617. wantsLLVMFunc = false;
  20618. }*/
  20619. if (wantsLLVMFunc)
  20620. {
  20621. func = GetIntrinsic(methodInstance, true);
  20622. if (func)
  20623. {
  20624. isIntrinsic = true;
  20625. }
  20626. else
  20627. {
  20628. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  20629. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  20630. if (methodInstance->mAlwaysInline)
  20631. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  20632. // if (prevFunc)
  20633. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  20634. }
  20635. methodInstance->mIRFunction = func;
  20636. //if (!ignoreWrites)
  20637. //BF_ASSERT(!func.IsFake());
  20638. }
  20639. }
  20640. if (outIsIntrinsic != NULL)
  20641. *outIsIntrinsic = isIntrinsic;
  20642. if (!isIntrinsic)
  20643. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  20644. }
  20645. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  20646. {
  20647. if (methodInstance->mHotMethod != NULL)
  20648. return;
  20649. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  20650. {
  20651. auto srcTypeInst = methodInstance->GetOwner();
  20652. if (srcTypeInst->mHotTypeData == NULL)
  20653. return;
  20654. StringT<128> mangledName = inMangledName;
  20655. if (mangledName.IsEmpty())
  20656. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  20657. // We always keep the current primary method at the same address
  20658. BfHotMethod* hotMethod;
  20659. BfHotMethod** hotMethodPtr;
  20660. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  20661. {
  20662. hotMethod = new BfHotMethod();
  20663. *hotMethodPtr = hotMethod;
  20664. hotMethod->mRefCount = 1;
  20665. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20666. #ifdef BF_DBG_HOTMETHOD_IDX
  20667. static int sMethodIdx = 0;
  20668. hotMethod->mMethodIdx = sMethodIdx++;
  20669. #endif
  20670. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20671. }
  20672. else
  20673. {
  20674. hotMethod = *hotMethodPtr;
  20675. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  20676. {
  20677. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  20678. auto prevHotMethod = *hotMethodPtr;
  20679. hotMethod = new BfHotMethod();
  20680. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20681. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  20682. hotDupMethod->mRefCount++;
  20683. prevHotMethod->mReferences.Add(hotDupMethod);
  20684. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  20685. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20686. }
  20687. else if (mCompiler->IsHotCompile())
  20688. {
  20689. // Link the previous version into the mPrevVersion
  20690. BfHotMethod* prevMethod = new BfHotMethod();
  20691. prevMethod->mRefCount = 1;
  20692. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  20693. hotMethod->mPrevVersion = prevMethod;
  20694. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  20695. hotMethod->mSrcTypeVersion = NULL;
  20696. prevMethod->mFlags = hotMethod->mFlags;
  20697. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  20698. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  20699. #ifdef BF_DBG_HOTMETHOD_NAME
  20700. prevMethod->mMangledName = hotMethod->mMangledName;
  20701. #endif
  20702. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  20703. }
  20704. else
  20705. {
  20706. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20707. hotMethod->Clear(true);
  20708. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20709. }
  20710. }
  20711. if (methodInstance->mIsClosure)
  20712. {
  20713. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  20714. }
  20715. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  20716. hotMethod->mSrcTypeVersion->mRefCount++;
  20717. hotMethod->mRefCount++;
  20718. #ifdef BF_DBG_HOTMETHOD_NAME
  20719. hotMethod->mMangledName = mangledName;
  20720. #endif
  20721. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!IsHotCompile()))
  20722. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  20723. methodInstance->mHotMethod = hotMethod;
  20724. }
  20725. }
  20726. static void StackOverflow()
  20727. {
  20728. int i = 0;
  20729. if (i == 0)
  20730. StackOverflow();
  20731. }
  20732. void BfModule::StartMethodDeclaration(BfMethodInstance* methodInstance, BfMethodState* prevMethodState)
  20733. {
  20734. methodInstance->mHasStartedDeclaration = true;
  20735. auto methodDef = methodInstance->mMethodDef;
  20736. auto typeInstance = methodInstance->GetOwner();
  20737. bool hasNonGenericParams = false;
  20738. bool hasGenericParams = false;
  20739. int dependentGenericStartIdx = 0;
  20740. if (methodDef->mIsLocalMethod)
  20741. {
  20742. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  20743. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  20744. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  20745. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  20746. // over the local method each time
  20747. auto rootMethodInstance = prevMethodState->GetRootMethodState()->mMethodInstance;
  20748. dependentGenericStartIdx = 0;
  20749. if (rootMethodInstance != NULL)
  20750. {
  20751. if (rootMethodInstance->mMethodInfoEx != NULL)
  20752. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  20753. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  20754. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  20755. }
  20756. }
  20757. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodInstance->GetNumGenericArguments(); genericArgIdx++)
  20758. {
  20759. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  20760. if (genericArgType->IsGenericParam())
  20761. {
  20762. hasGenericParams = true;
  20763. auto genericParam = (BfGenericParamType*)genericArgType;
  20764. methodInstance->mIsUnspecialized = true;
  20765. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  20766. methodInstance->mIsUnspecializedVariation = true;
  20767. }
  20768. else
  20769. {
  20770. hasNonGenericParams = true;
  20771. if (genericArgType->IsUnspecializedType())
  20772. {
  20773. methodInstance->mIsUnspecialized = true;
  20774. methodInstance->mIsUnspecializedVariation = true;
  20775. }
  20776. }
  20777. }
  20778. if ((hasGenericParams) && (hasNonGenericParams))
  20779. {
  20780. methodInstance->mIsUnspecializedVariation = true;
  20781. }
  20782. if (typeInstance->IsUnspecializedType())
  20783. {
  20784. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  20785. // actually want to do method processing on it
  20786. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  20787. methodInstance->mIsUnspecializedVariation = true;
  20788. methodInstance->mIsUnspecialized = true;
  20789. }
  20790. if (methodInstance->mIsUnspecializedVariation)
  20791. BF_ASSERT(methodInstance->mIsUnspecialized);
  20792. //TODO: Why did we do this?
  20793. if (methodDef->mMethodType == BfMethodType_Mixin)
  20794. {
  20795. if (methodInstance->IsSpecializedGenericMethod())
  20796. methodInstance->mIsUnspecializedVariation = true;
  20797. methodInstance->mIsUnspecialized = true;
  20798. }
  20799. }
  20800. // methodDeclaration is NULL for default constructors
  20801. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  20802. {
  20803. BF_ASSERT((mCompiler->mCeMachine == NULL) || (!mCompiler->mCeMachine->mDbgPaused));
  20804. BP_ZONE("BfModule::DoMethodDeclaration");
  20805. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  20806. // to effectively make mIgnoreWrites method-scoped
  20807. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  20808. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  20809. SetAndRestoreValue<bool> prevAllowLockYield(mContext->mAllowLockYield, false);
  20810. BfTypeState typeState(mCurTypeInstance);
  20811. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20812. BfModule* resolveModule = mContext->mUnreifiedModule;
  20813. if (mCompiler->IsAutocomplete())
  20814. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  20815. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  20816. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  20817. BfMethodState methodState;
  20818. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  20819. methodState.mTempKind = BfMethodState::TempKind_Static;
  20820. defer({ mCurMethodInstance->mHasBeenDeclared = true; });
  20821. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  20822. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  20823. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  20824. // if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  20825. // {
  20826. // BF_ASSERT(mContext->mResolvingVarField);
  20827. // isTemporaryFunc = true;
  20828. // }
  20829. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  20830. FinishInit();
  20831. auto typeInstance = mCurTypeInstance;
  20832. auto typeDef = typeInstance->mTypeDef;
  20833. auto methodDef = mCurMethodInstance->mMethodDef;
  20834. if (methodDef->mName.StartsWith('_'))
  20835. {
  20836. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  20837. if (methodDef->mName == "__FATALERRORNAME")
  20838. BFMODULE_FATAL(this, "__FATALERRORNAME");
  20839. if (methodDef->mName == "__STACKOVERFLOW")
  20840. StackOverflow();
  20841. if (methodDef->mName == "__INTERNALERROR")
  20842. InternalError("Bad method name", methodDef->GetRefNode());
  20843. }
  20844. if (typeInstance->IsClosure())
  20845. {
  20846. if (methodDef->mName == "Invoke")
  20847. return;
  20848. }
  20849. auto methodInstance = mCurMethodInstance;
  20850. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  20851. addToWorkList = false;
  20852. if (!methodInstance->mHasStartedDeclaration)
  20853. StartMethodDeclaration(methodInstance, prevMethodState.mPrevVal);
  20854. BfAutoComplete* bfAutocomplete = NULL;
  20855. if (mCompiler->mResolvePassData != NULL)
  20856. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  20857. if (methodInstance->mMethodInfoEx != NULL)
  20858. {
  20859. BfTypeInstance* unspecializedTypeInstance = NULL;
  20860. Array<BfTypeReference*> deferredResolveTypes;
  20861. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  20862. {
  20863. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  20864. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  20865. {
  20866. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  20867. }
  20868. else
  20869. {
  20870. auto externConstraintDef = genericParam->GetExternConstraintDef();
  20871. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  20872. auto autoComplete = mCompiler->GetAutoComplete();
  20873. if (autoComplete != NULL)
  20874. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  20875. if (genericParam->mExternType != NULL)
  20876. {
  20877. //
  20878. }
  20879. else
  20880. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  20881. }
  20882. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized, &deferredResolveTypes);
  20883. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  20884. {
  20885. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  20886. if (bfAutocomplete != NULL)
  20887. {
  20888. for (auto nameNode : genericParamDef->mNameNodes)
  20889. {
  20890. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  20891. }
  20892. }
  20893. }
  20894. }
  20895. for (auto typeRef : deferredResolveTypes)
  20896. auto constraintType = ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_None);
  20897. if (methodInstance->mMethodInfoEx != NULL)
  20898. {
  20899. ValidateGenericParams(BfGenericParamKind_Method,
  20900. Span<BfGenericParamInstance*>((BfGenericParamInstance**)methodInstance->mMethodInfoEx->mGenericParams.mVals,
  20901. methodInstance->mMethodInfoEx->mGenericParams.mSize));
  20902. }
  20903. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  20904. AddDependency(genericParam, mCurTypeInstance);
  20905. }
  20906. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  20907. {
  20908. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  20909. BfAstNode* nameNode = methodDeclaration->mNameNode;
  20910. if (nameNode == NULL)
  20911. {
  20912. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  20913. nameNode = ctorDeclaration->mThisToken;
  20914. }
  20915. if ((autoComplete->IsAutocompleteNode(nameNode)) && (autoComplete->mResolveType != BfResolveType_Autocomplete))
  20916. {
  20917. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  20918. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  20919. autoComplete->mDefType = typeDef;
  20920. autoComplete->mDefMethod = methodDef;
  20921. autoComplete->SetDefinitionLocation(nameNode);
  20922. if (methodDef->mIsOverride)
  20923. {
  20924. bool found = false;
  20925. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  20926. {
  20927. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  20928. if (ventry.mDeclaringMethod.mMethodNum == -1)
  20929. continue;
  20930. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  20931. if (virtMethod != NULL)
  20932. {
  20933. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  20934. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  20935. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  20936. {
  20937. // Is matching method
  20938. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  20939. {
  20940. auto baseType = typeInstance->mBaseType;
  20941. if (baseType != NULL)
  20942. {
  20943. found = true;
  20944. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  20945. baseType = baseType->mBaseType;
  20946. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  20947. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  20948. autoComplete->mDefType = baseType->mTypeDef;
  20949. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  20950. }
  20951. }
  20952. break;
  20953. }
  20954. }
  20955. }
  20956. if ((!found) && (autoComplete->mIsGetDefinition) && (methodDef->mDeclaringType->IsExtension()))
  20957. {
  20958. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  20959. {
  20960. auto defaultMethod = methodGroup.mDefault;
  20961. if (defaultMethod == NULL)
  20962. continue;
  20963. if (!defaultMethod->mMethodDef->mIsExtern)
  20964. continue;
  20965. if (!CompareMethodSignatures(defaultMethod, methodInstance))
  20966. continue;
  20967. autoComplete->SetDefinitionLocation(defaultMethod->mMethodDef->GetRefNode(), true);
  20968. autoComplete->mDefType = typeInstance->mTypeDef;
  20969. autoComplete->mDefMethod = defaultMethod->mMethodDef;
  20970. }
  20971. }
  20972. }
  20973. }
  20974. }
  20975. bool reportErrors = true;
  20976. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  20977. reportErrors = true;
  20978. // Only the defining contexts needs to report errors here
  20979. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  20980. if (methodDef->mMethodType == BfMethodType_Dtor)
  20981. {
  20982. if (methodDef->mIsStatic)
  20983. {
  20984. }
  20985. else
  20986. {
  20987. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  20988. {
  20989. BfAstNode* refNode = methodDeclaration;
  20990. if (refNode == NULL)
  20991. {
  20992. // Whatever caused this ctor to be generated should have caused another failure
  20993. // But that failure might not be generated until the ctor is generated
  20994. }
  20995. else
  20996. {
  20997. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  20998. if (dtorDecl != NULL)
  20999. refNode = dtorDecl->mThisToken;
  21000. Fail("Structs cannot have destructors", refNode);
  21001. }
  21002. }
  21003. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21004. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  21005. (mCurTypeInstance != mContext->mBfObjectType))
  21006. {
  21007. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  21008. }
  21009. }
  21010. }
  21011. BfType* resolvedReturnType = NULL;
  21012. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  21013. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  21014. (methodDef->mReturnTypeRef != NULL))
  21015. {
  21016. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  21017. if (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>())
  21018. {
  21019. // An invalid 'var' error would not have been caught in the original property type pass
  21020. mIgnoreErrors = false;
  21021. }
  21022. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_NoReify);
  21023. if ((((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0) || (methodInstance->mIsAutocompleteMethod))
  21024. && (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>()))
  21025. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  21026. else
  21027. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration, flags);
  21028. if (resolvedReturnType == NULL)
  21029. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  21030. if ((methodDef->mIsReadOnly) && (!resolvedReturnType->IsRef()))
  21031. {
  21032. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration))
  21033. if (methodDeclaration->mReadOnlySpecifier != NULL)
  21034. Fail("Readonly specifier is only valid on 'ref' return types", methodDeclaration->mReadOnlySpecifier);
  21035. }
  21036. }
  21037. else
  21038. {
  21039. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  21040. }
  21041. BF_ASSERT(resolvedReturnType != NULL);
  21042. mCurMethodInstance->mReturnType = resolvedReturnType;
  21043. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  21044. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  21045. //if (!methodInstance->IsSpecializedGenericMethod())
  21046. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21047. if (methodDef->mExplicitInterface != NULL)
  21048. {
  21049. auto autoComplete = mCompiler->GetAutoComplete();
  21050. if (autoComplete != NULL)
  21051. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  21052. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  21053. BfTypeInstance* explicitInterface = NULL;
  21054. if (explicitType != NULL)
  21055. explicitInterface = explicitType->ToTypeInstance();
  21056. if (explicitInterface != NULL)
  21057. {
  21058. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  21059. if (autoComplete != NULL)
  21060. {
  21061. BfTokenNode* dotToken = NULL;
  21062. BfAstNode* nameNode = NULL;
  21063. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  21064. {
  21065. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  21066. nameNode = methodDeclaration->mNameNode;
  21067. }
  21068. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  21069. }
  21070. }
  21071. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  21072. {
  21073. bool interfaceFound = false;
  21074. for (auto ifaceInst : typeInstance->mInterfaces)
  21075. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  21076. if ((!interfaceFound) && (!typeInstance->mTypeFailed))
  21077. {
  21078. if (methodDef->mMethodDeclaration != NULL)
  21079. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  21080. else
  21081. {
  21082. // For property decls, we should have already given the error during type population
  21083. if (mCompiler->mRevision == 1)
  21084. AssertErrorState();
  21085. }
  21086. }
  21087. }
  21088. }
  21089. bool isThisStruct = mCurTypeInstance->IsStruct();
  21090. BfType* thisType = NULL;
  21091. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  21092. {
  21093. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  21094. {
  21095. thisType = mCurTypeInstance;
  21096. if (thisType == NULL)
  21097. return;
  21098. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  21099. {
  21100. BfTypeUtils::SplatIterate([&](BfType* checkType)
  21101. {
  21102. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  21103. }, thisType);
  21104. }
  21105. }
  21106. else
  21107. {
  21108. thisType = mCurTypeInstance;
  21109. resolveModule->PopulateType(thisType, BfPopulateType_Declaration);
  21110. }
  21111. }
  21112. int implicitParamCount = 0;
  21113. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  21114. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  21115. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  21116. bool hadDelegateParams = false;
  21117. bool hadParams = false;
  21118. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  21119. {
  21120. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  21121. BfParameterDef* paramDef = NULL;
  21122. int paramDefIdx = -1;
  21123. if (paramIdx < implicitParamCount)
  21124. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  21125. else
  21126. {
  21127. paramDefIdx = paramIdx - implicitParamCount;
  21128. paramDef = methodDef->mParams[paramDefIdx];
  21129. }
  21130. if (hadParams)
  21131. break;
  21132. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  21133. continue;
  21134. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  21135. (paramDef->mParamKind != BfParamKind_AppendIdx))
  21136. {
  21137. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  21138. if (mCompiler->mResolvePassData->mAutoComplete->IsAutocompleteNode(paramDef->mTypeRef))
  21139. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("token", "in"), paramDef->mTypeRef->ToString());
  21140. }
  21141. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  21142. {
  21143. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  21144. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  21145. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  21146. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  21147. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  21148. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  21149. }
  21150. BfType* resolvedParamType = NULL;
  21151. if (closureCaptureEntry != NULL)
  21152. resolvedParamType = closureCaptureEntry->mType;
  21153. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfLetTypeReference>()))
  21154. {
  21155. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  21156. resolvedParamType = mContext->mBfObjectType;
  21157. }
  21158. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfVarTypeReference>()))
  21159. {
  21160. if (methodDef->mMethodType != BfMethodType_Mixin)
  21161. {
  21162. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  21163. resolvedParamType = mContext->mBfObjectType;
  21164. }
  21165. else
  21166. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21167. }
  21168. BfType* unresolvedParamType = resolvedParamType;
  21169. bool wasGenericParam = false;
  21170. if (resolvedParamType == NULL)
  21171. {
  21172. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue | BfResolveTypeRefFlag_NoReify);
  21173. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  21174. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  21175. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  21176. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  21177. resolvedParamType = resolvedParamType->GetUnderlyingType();
  21178. }
  21179. if (resolvedParamType == NULL)
  21180. {
  21181. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21182. unresolvedParamType = resolvedParamType;
  21183. if (mCurTypeInstance->IsBoxed())
  21184. {
  21185. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  21186. // If we failed a lookup here then we better have also failed it in the original type
  21187. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.ContainsKey(boxedType->mElementType->ToTypeInstance()));
  21188. }
  21189. }
  21190. BF_ASSERT(!resolvedParamType->IsDeleting());
  21191. if (!methodInstance->IsSpecializedGenericMethod())
  21192. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21193. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  21194. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  21195. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  21196. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  21197. {
  21198. if (paramDef->mParamKind == BfParamKind_Params)
  21199. {
  21200. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  21201. if (refNode != NULL)
  21202. refNode = paramDef->mParamDeclaration->mModToken;
  21203. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  21204. }
  21205. BfTypedValue defaultValue;
  21206. if (resolvedParamType->IsConstExprValue())
  21207. {
  21208. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  21209. BfExprEvaluator exprEvaluator(this);
  21210. exprEvaluator.mExpectingType = constExprType->mType;
  21211. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  21212. defaultValue = exprEvaluator.GetResult();
  21213. }
  21214. else
  21215. {
  21216. BfTypeState typeState;
  21217. typeState.mType = mCurTypeInstance;
  21218. typeState.mCurTypeDef = methodDef->mDeclaringType;
  21219. //typeState.mCurMethodDef = methodDef;
  21220. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  21221. BfConstResolver constResolver(this);
  21222. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  21223. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  21224. {
  21225. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  21226. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  21227. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  21228. {
  21229. defaultValue = castedDefaultValue; // Good!
  21230. }
  21231. else if (!CanCast(defaultValue, resolvedParamType))
  21232. {
  21233. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  21234. // a conversion operator.
  21235. // This should throw an error
  21236. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  21237. AssertErrorState();
  21238. if (!defaultValue.mValue.IsConst())
  21239. defaultValue = BfTypedValue();
  21240. }
  21241. }
  21242. }
  21243. if (!defaultValue)
  21244. {
  21245. defaultValue = GetDefaultTypedValue(resolvedParamType);
  21246. if (!defaultValue.mValue.IsConst())
  21247. defaultValue = BfTypedValue();
  21248. }
  21249. if (defaultValue)
  21250. {
  21251. if (defaultValue.mType->IsVar())
  21252. {
  21253. AssertErrorState();
  21254. }
  21255. else
  21256. {
  21257. BF_ASSERT(defaultValue.mValue.IsConst());
  21258. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  21259. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  21260. CurrentAddToConstHolder(defaultValue.mValue);
  21261. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  21262. }
  21263. }
  21264. }
  21265. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  21266. {
  21267. bool addParams = true;
  21268. bool isValid = false;
  21269. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  21270. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->IsInstanceOf(mCompiler->mSpanTypeDef)))
  21271. {
  21272. // Span<T>
  21273. isValid = true;
  21274. }
  21275. else if (resolvedParamType->IsArray())
  21276. {
  21277. // Array is the 'normal' params type
  21278. isValid = true;
  21279. }
  21280. else if (resolvedParamType->IsSizedArray())
  21281. {
  21282. isValid = true;
  21283. }
  21284. else if (resolvedParamType->IsVar())
  21285. {
  21286. isValid = true;
  21287. }
  21288. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()) || (resolvedParamType->IsMethodRef()))
  21289. {
  21290. hadDelegateParams = true;
  21291. // This means we copy the params from a delegate
  21292. BfMethodParam methodParam;
  21293. methodParam.mResolvedType = resolvedParamType;
  21294. methodParam.mParamDefIdx = paramDefIdx;
  21295. methodParam.mDelegateParamIdx = 0;
  21296. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21297. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  21298. {
  21299. methodParam.mDelegateParamIdx = delegateParamIdx;
  21300. mCurMethodInstance->mParams.Add(methodParam);
  21301. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  21302. if (!methodInstance->IsSpecializedGenericMethod())
  21303. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21304. }
  21305. isValid = true;
  21306. addParams = false;
  21307. }
  21308. else if (resolvedParamType->IsGenericParam())
  21309. {
  21310. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  21311. if (genericParamInstance->mTypeConstraint != NULL)
  21312. {
  21313. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  21314. if ((genericParamInstance->mTypeConstraint->IsArray()) || (genericParamInstance->mTypeConstraint->IsSizedArray()))
  21315. {
  21316. BfMethodParam methodParam;
  21317. methodParam.mResolvedType = resolvedParamType;
  21318. methodParam.mParamDefIdx = paramDefIdx;
  21319. mCurMethodInstance->mParams.Add(methodParam);
  21320. isValid = true;
  21321. }
  21322. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  21323. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  21324. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  21325. {
  21326. mCurMethodInstance->mHadGenericDelegateParams = true;
  21327. isValid = true;
  21328. addParams = false;
  21329. }
  21330. }
  21331. }
  21332. else
  21333. {
  21334. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  21335. if ((paramTypeInst != NULL) &&
  21336. ((paramTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef))))
  21337. {
  21338. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  21339. isValid = true;
  21340. addParams = false;
  21341. }
  21342. }
  21343. if (!isValid)
  21344. {
  21345. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  21346. // Failure case, make it an Object[]
  21347. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  21348. }
  21349. if ((addParams) && (resolvedParamType != NULL))
  21350. {
  21351. BfMethodParam methodParam;
  21352. methodParam.mResolvedType = resolvedParamType;
  21353. methodParam.mParamDefIdx = paramDefIdx;
  21354. mCurMethodInstance->mParams.push_back(methodParam);
  21355. }
  21356. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  21357. {
  21358. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  21359. }
  21360. }
  21361. else
  21362. {
  21363. BfMethodParam methodParam;
  21364. methodParam.mResolvedType = resolvedParamType;
  21365. methodParam.mParamDefIdx = paramDefIdx;
  21366. mCurMethodInstance->mParams.Add(methodParam);
  21367. }
  21368. }
  21369. if (hadDelegateParams)
  21370. {
  21371. HashSet<String> usedNames;
  21372. Dictionary<int, int> usedParamDefIdx;
  21373. for (auto methodParam : methodDef->mParams)
  21374. {
  21375. usedNames.Add(methodParam->mName);
  21376. }
  21377. for (auto& methodParam : mCurMethodInstance->mParams)
  21378. {
  21379. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  21380. {
  21381. int* refCount = NULL;
  21382. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  21383. (*refCount)++;
  21384. }
  21385. }
  21386. for (auto& methodParam : mCurMethodInstance->mParams)
  21387. {
  21388. if (methodParam.mDelegateParamIdx != -1)
  21389. {
  21390. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  21391. methodParam.mDelegateParamNameCombine = true;
  21392. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21393. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  21394. if (usedNames.Contains(paramName))
  21395. methodParam.mDelegateParamNameCombine = true;
  21396. }
  21397. }
  21398. }
  21399. int argIdx = 0;
  21400. resolveModule->PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  21401. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  21402. {
  21403. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  21404. auto thisType = methodInstance->GetOwner();
  21405. if (methodInstance->GetParamIsSplat(thisIdx))
  21406. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  21407. else if (!thisType->IsValuelessType())
  21408. {
  21409. BfTypeCode loweredTypeCode = BfTypeCode_None;
  21410. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  21411. if ((!mIsComptimeModule) && (!methodDef->mIsMutating))
  21412. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  21413. argIdx++;
  21414. if (loweredTypeCode2 != BfTypeCode_None)
  21415. argIdx++;
  21416. }
  21417. }
  21418. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  21419. argIdx++;
  21420. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  21421. {
  21422. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  21423. BfType* checkType = methodParam.mResolvedType;
  21424. int checkArgIdx = argIdx;
  21425. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  21426. {
  21427. checkArgIdx = 0;
  21428. checkType = methodInstance->GetThisType();
  21429. }
  21430. if (checkType->IsMethodRef())
  21431. {
  21432. methodParam.mIsSplat = true;
  21433. }
  21434. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting(paramIdx)))
  21435. {
  21436. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  21437. if (checkType->IsSplattable())
  21438. {
  21439. bool isSplat = false;
  21440. auto checkTypeInstance = checkType->ToTypeInstance();
  21441. if ((checkTypeInstance != NULL) && (checkTypeInstance->mIsCRepr))
  21442. isSplat = true;
  21443. int splatCount = checkType->GetSplatCount();
  21444. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  21445. isSplat = true;
  21446. if (isSplat)
  21447. {
  21448. methodParam.mIsSplat = true;
  21449. argIdx += splatCount;
  21450. continue;
  21451. }
  21452. }
  21453. else if (!checkType->IsValuelessType())
  21454. {
  21455. BfTypeCode loweredTypeCode = BfTypeCode_None;
  21456. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  21457. if (!mIsComptimeModule)
  21458. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  21459. argIdx++;
  21460. if (loweredTypeCode2 != BfTypeCode_None)
  21461. argIdx++;
  21462. continue;
  21463. }
  21464. }
  21465. argIdx++;
  21466. }
  21467. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  21468. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  21469. {
  21470. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  21471. }
  21472. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  21473. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  21474. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  21475. (!methodDef->mIsSkipCall))
  21476. {
  21477. if (methodDeclaration->mEndSemicolon == NULL)
  21478. {
  21479. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  21480. {
  21481. //
  21482. }
  21483. else
  21484. AssertParseErrorState();
  21485. }
  21486. else
  21487. {
  21488. bool isError = true;
  21489. if (typeInstance->IsTypedPrimitive())
  21490. {
  21491. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  21492. {
  21493. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  21494. {
  21495. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  21496. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  21497. {
  21498. isError = false;
  21499. }
  21500. }
  21501. }
  21502. }
  21503. if (isError)
  21504. {
  21505. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  21506. MethodToString(methodInstance).c_str()),
  21507. methodDef->GetRefNode());
  21508. }
  21509. }
  21510. }
  21511. if (methodDef->IsEmptyPartial())
  21512. hasExternSpecifier = true;
  21513. if (!methodInstance->IsAutocompleteMethod())
  21514. {
  21515. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  21516. int implicitParamCount = methodInstance->GetImplicitParamCount();
  21517. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  21518. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  21519. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  21520. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  21521. int paramIdx = 0;
  21522. int defaultParamIdx = 0;
  21523. while (true)
  21524. {
  21525. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  21526. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  21527. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  21528. {
  21529. paramIdx++;
  21530. continue;
  21531. }
  21532. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  21533. {
  21534. defaultParamIdx++;
  21535. continue;
  21536. }
  21537. if ((isDone) || (isDefaultDone))
  21538. {
  21539. // 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
  21540. // to cause us to throw an assertion in the declaration here
  21541. if ((!defaultMethodInstance->mHadGenericDelegateParams) && (!methodInstance->mHasFailed) && (!defaultMethodInstance->mHasFailed))
  21542. BF_ASSERT((isDone) && (isDefaultDone));
  21543. break;
  21544. }
  21545. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  21546. if (paramType->IsRef())
  21547. paramType = paramType->GetUnderlyingType();
  21548. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  21549. paramIdx++;
  21550. defaultParamIdx++;
  21551. }
  21552. }
  21553. StringT<4096> mangledName;
  21554. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  21555. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  21556. {
  21557. auto paramType = methodInstance->GetParamType(paramIdx);
  21558. if (paramType->IsComposite())
  21559. resolveModule->PopulateType(paramType, BfPopulateType_Data);
  21560. if (!methodInstance->IsParamSkipped(paramIdx))
  21561. {
  21562. if (paramType->IsStruct())
  21563. {
  21564. //
  21565. }
  21566. else
  21567. {
  21568. PopulateType(paramType, BfPopulateType_Declaration);
  21569. }
  21570. }
  21571. }
  21572. // Only process method in default unspecialized mode, not in variations
  21573. if (methodInstance->mIsUnspecializedVariation)
  21574. return;
  21575. resolveModule->PopulateType(resolvedReturnType, BfPopulateType_Data);
  21576. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  21577. if (resolvedReturnType->IsValuelessType())
  21578. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  21579. if (!mBfIRBuilder->mIgnoreWrites)
  21580. {
  21581. bool isIntrinsic = false;
  21582. if (!methodInstance->mIRFunction)
  21583. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  21584. if (isIntrinsic)
  21585. {
  21586. addToWorkList = false;
  21587. }
  21588. }
  21589. else
  21590. {
  21591. GetMethodCustomAttributes(methodInstance);
  21592. }
  21593. auto func = methodInstance->mIRFunction;
  21594. // if (methodInstance->mIsReified)
  21595. // CheckHotMethod(methodInstance, mangledName);
  21596. for (auto& param : methodInstance->mParams)
  21597. {
  21598. BF_ASSERT(!param.mResolvedType->IsDeleting());
  21599. }
  21600. 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);
  21601. SizedArray<BfIRMDNode, 8> diParams;
  21602. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  21603. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  21604. {
  21605. //CS0708
  21606. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  21607. }
  21608. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  21609. {
  21610. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  21611. methodDef->mIsVirtual = false;
  21612. }
  21613. BfAstNode* mutSpecifier = NULL;
  21614. if (methodDeclaration != NULL)
  21615. mutSpecifier = methodDeclaration->mMutSpecifier;
  21616. else if (methodDef->GetPropertyMethodDeclaration() != NULL)
  21617. {
  21618. mutSpecifier = methodDef->GetPropertyMethodDeclaration()->mMutSpecifier;
  21619. if (mutSpecifier == NULL)
  21620. {
  21621. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21622. if (propertyDeclaration != NULL)
  21623. {
  21624. if (auto propExprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  21625. mutSpecifier = propExprBody->mMutSpecifier;
  21626. }
  21627. }
  21628. }
  21629. if ((mutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  21630. {
  21631. if (methodDef->mIsStatic)
  21632. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", mutSpecifier);
  21633. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  21634. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", mutSpecifier);
  21635. else if (methodDef->mMethodType == BfMethodType_Ctor)
  21636. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", mutSpecifier);
  21637. else if (methodDef->mMethodType == BfMethodType_Dtor)
  21638. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", mutSpecifier);
  21639. }
  21640. if (isTemporaryFunc)
  21641. {
  21642. // This handles temporary methods for autocomplete types
  21643. //BF_ASSERT(mIsScratchModule);
  21644. //BF_ASSERT(mCompiler->IsAutocomplete());
  21645. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  21646. return; // Bail out early for autocomplete pass
  21647. }
  21648. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  21649. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  21650. // autocompleter. Why did we have this check anyway?
  21651. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  21652. {
  21653. AddMethodReference(methodInstance);
  21654. mFuncReferences[methodInstance] = func;
  21655. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  21656. }*/
  21657. if (mParentModule != NULL)
  21658. {
  21659. // For extension modules we need to keep track of our own methods so we can know which methods
  21660. // we have defined ourselves and which are from the parent module or other extensions
  21661. if (!func.IsFake())
  21662. {
  21663. if (func)
  21664. mFuncReferences[methodInstance] = func;
  21665. }
  21666. }
  21667. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  21668. {
  21669. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  21670. auto owningModule = methodInstance->GetOwner()->mModule;
  21671. if (!owningModule->mIsScratchModule)
  21672. owningModule->mOnDemandMethodCount++;
  21673. VerifyOnDemandMethods();
  21674. }
  21675. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  21676. if (wasAwaitingDecl)
  21677. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  21678. if (addToWorkList)
  21679. {
  21680. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  21681. {
  21682. AddMethodToWorkList(methodInstance);
  21683. }
  21684. else
  21685. {
  21686. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  21687. methodInstance->mIgnoreBody = true;
  21688. if (typeInstance->IsUnspecializedType())
  21689. {
  21690. // Don't hold on to actual Function for unspecialized types
  21691. methodInstance->mIRFunction = BfIRFunction();
  21692. }
  21693. }
  21694. }
  21695. else
  21696. {
  21697. //BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  21698. }
  21699. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  21700. (!methodDef->mIsLocalMethod) &&
  21701. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  21702. (!methodDef->mReturnTypeRef->IsTemporary()))
  21703. {
  21704. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  21705. {
  21706. //TODO:
  21707. //CS0053
  21708. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  21709. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  21710. methodDef->mReturnTypeRef, true);
  21711. }
  21712. else
  21713. {
  21714. //CS0050
  21715. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  21716. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  21717. methodDef->mReturnTypeRef, true);
  21718. }
  21719. }
  21720. if (typeInstance->IsInterface())
  21721. {
  21722. if (methodDef->mMethodType == BfMethodType_Ctor)
  21723. Fail("Interfaces cannot contain constructors", methodDeclaration);
  21724. if (methodDeclaration != NULL)
  21725. {
  21726. if (methodDef->mBody == NULL)
  21727. {
  21728. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  21729. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  21730. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  21731. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  21732. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  21733. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  21734. }
  21735. }
  21736. }
  21737. bool foundHiddenMethod = false;
  21738. BfTokenNode* virtualToken = NULL;
  21739. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21740. if (propertyDeclaration != NULL)
  21741. virtualToken = propertyDeclaration->mVirtualSpecifier;
  21742. else if (methodDeclaration != NULL)
  21743. virtualToken = methodDeclaration->mVirtualSpecifier;
  21744. // Don't compare specialized generic methods against normal methods
  21745. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  21746. (!methodDef->mIsLocalMethod) && (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  21747. {
  21748. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  21749. {
  21750. typeDef->PopulateMemberSets();
  21751. BfMethodDef* nextMethod = NULL;
  21752. BfMemberSetEntry* entry = NULL;
  21753. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21754. nextMethod = (BfMethodDef*)entry->mMemberDef;
  21755. while (nextMethod != NULL)
  21756. {
  21757. auto checkMethod = nextMethod;
  21758. nextMethod = nextMethod->mNextWithSameName;
  21759. if (checkMethod == methodDef)
  21760. continue;
  21761. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21762. if (checkMethodInstance == NULL)
  21763. {
  21764. if ((methodDef->mDeclaringType->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension()))
  21765. checkMethodInstance = GetRawMethodInstanceAtIdx(typeInstance, checkMethod->mIdx);
  21766. if (checkMethodInstance == NULL)
  21767. continue;
  21768. }
  21769. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  21770. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  21771. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  21772. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  21773. {
  21774. bool canChain = false;
  21775. if ((methodDef->mParams.empty()) &&
  21776. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  21777. {
  21778. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  21779. canChain = true;
  21780. else if (methodDef->mMethodType == BfMethodType_Normal)
  21781. {
  21782. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  21783. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  21784. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  21785. canChain = true;
  21786. }
  21787. }
  21788. if (canChain)
  21789. {
  21790. bool isBetter;
  21791. bool isWorse;
  21792. CompareDeclTypes(typeInstance, checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  21793. if (isBetter && !isWorse)
  21794. {
  21795. methodInstance->mChainType = BfMethodChainType_ChainHead;
  21796. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  21797. }
  21798. else
  21799. {
  21800. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  21801. methodInstance->mChainType = BfMethodChainType_ChainMember;
  21802. }
  21803. }
  21804. else
  21805. {
  21806. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  21807. continue;
  21808. bool silentlyAllow = false;
  21809. bool extensionWarn = false;
  21810. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  21811. {
  21812. if (typeInstance->IsInterface())
  21813. {
  21814. if (methodDef->mIsOverride)
  21815. silentlyAllow = true;
  21816. }
  21817. else
  21818. {
  21819. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  21820. {
  21821. silentlyAllow = true;
  21822. methodInstance->mIsInnerOverride = true;
  21823. CheckOverridenMethod(methodInstance, checkMethodInstance);
  21824. }
  21825. else if (!checkMethod->mDeclaringType->IsExtension())
  21826. {
  21827. foundHiddenMethod = true;
  21828. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  21829. silentlyAllow = true;
  21830. else if (methodDef->mIsNew)
  21831. {
  21832. silentlyAllow = true;
  21833. }
  21834. else if (checkMethod->GetMethodDeclaration() == NULL)
  21835. silentlyAllow = true;
  21836. else if (methodDef->mIsOverride)
  21837. silentlyAllow = true;
  21838. else
  21839. extensionWarn = true;
  21840. }
  21841. else
  21842. silentlyAllow = true;
  21843. }
  21844. }
  21845. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  21846. silentlyAllow = true;
  21847. if (checkMethod->mMethodDeclaration == NULL)
  21848. {
  21849. // This can allow emission of a default ctor if we've already auto-added a default ctor
  21850. silentlyAllow = true;
  21851. }
  21852. if (!silentlyAllow)
  21853. {
  21854. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  21855. {
  21856. auto refNode = methodDef->GetRefNode();
  21857. BfError* bfError;
  21858. if (extensionWarn)
  21859. {
  21860. if (methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject)
  21861. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  21862. 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'.",
  21863. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  21864. else
  21865. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  21866. "This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional.", refNode);
  21867. }
  21868. else
  21869. {
  21870. bfError = Fail(StrFormat("Method '%s' already declared with the same parameter types", MethodToString(checkMethodInstance).c_str()), refNode, true);
  21871. }
  21872. if ((bfError != NULL) && (checkMethod->GetRefNode() != refNode))
  21873. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  21874. }
  21875. }
  21876. }
  21877. }
  21878. }
  21879. }
  21880. // Virtual methods give their error while slotting
  21881. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  21882. (!methodDef->mIsLocalMethod) &&
  21883. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  21884. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  21885. {
  21886. auto baseType = typeInstance->mBaseType;
  21887. while (baseType != NULL)
  21888. {
  21889. auto baseTypeDef = baseType->mTypeDef;
  21890. baseTypeDef->PopulateMemberSets();
  21891. BfMethodDef* checkMethod = NULL;
  21892. BfMemberSetEntry* entry = NULL;
  21893. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21894. checkMethod = (BfMethodDef*)entry->mMemberDef;
  21895. while (checkMethod != NULL)
  21896. {
  21897. if (checkMethod->mMethodDeclaration == NULL)
  21898. {
  21899. checkMethod = checkMethod->mNextWithSameName;
  21900. continue;
  21901. }
  21902. if (baseType->mMethodInstanceGroups.size() == 0)
  21903. {
  21904. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  21905. break;
  21906. }
  21907. if (checkMethod == methodDef)
  21908. {
  21909. checkMethod = checkMethod->mNextWithSameName;
  21910. continue;
  21911. }
  21912. if (checkMethod->mName != methodDef->mName)
  21913. {
  21914. checkMethod = checkMethod->mNextWithSameName;
  21915. continue;
  21916. }
  21917. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  21918. if (checkMethodInstance != NULL)
  21919. {
  21920. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  21921. (checkMethod->mProtection != BfProtection_Private) &&
  21922. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  21923. {
  21924. if ((!methodDef->mIsNew) && (!checkMethod->mDeclaringType->IsExtension()))
  21925. {
  21926. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  21927. if (refNode != NULL)
  21928. {
  21929. 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?
  21930. if (bfError != NULL)
  21931. {
  21932. bfError->mIsPersistent = true;
  21933. mCompiler->mPassInstance->MoreInfo("See inherited method", checkMethod->GetRefNode());
  21934. }
  21935. }
  21936. }
  21937. foundHiddenMethod = true;
  21938. break;
  21939. }
  21940. }
  21941. checkMethod = checkMethod->mNextWithSameName;
  21942. }
  21943. if (foundHiddenMethod)
  21944. break;
  21945. baseType = baseType->mBaseType;
  21946. }
  21947. if ((methodDef->mIsNew) && (!foundHiddenMethod) && (!mCurTypeInstance->IsSpecializedType()))
  21948. {
  21949. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21950. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  21951. methodDeclaration->mNewSpecifier;
  21952. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  21953. }
  21954. }
  21955. }
  21956. if ((methodDef->mIsConcrete) && (!methodInstance->mIsForeignMethodDef) && (!mCurTypeInstance->IsInterface()))
  21957. {
  21958. Fail("Only interfaces methods can be declared as 'concrete'", methodDeclaration->mVirtualSpecifier);
  21959. }
  21960. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic) && (!methodInstance->mIsInnerOverride))
  21961. {
  21962. if ((virtualToken != NULL) && (virtualToken->mToken == BfToken_Override) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  21963. Fail("No suitable method found to override", virtualToken, true);
  21964. else
  21965. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  21966. }
  21967. else if (methodDef->mIsVirtual)
  21968. {
  21969. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  21970. Fail("Virtual or abstract members cannot be 'private'", virtualToken, true);
  21971. if ((methodDef->mProtection == BfProtection_Internal) && (virtualToken != NULL))
  21972. Fail("Virtual or abstract members cannot be 'internal'. Consider using the 'protected internal' access specifier.", virtualToken, true);
  21973. }
  21974. mCompiler->mStats.mMethodDeclarations++;
  21975. mCompiler->UpdateCompletion();
  21976. }
  21977. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  21978. {
  21979. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  21980. auto typeInstance = mCurTypeInstance;
  21981. auto methodDef = methodInstance->mMethodDef;
  21982. int virtualMethodMatchIdx = -1;
  21983. if (typeInstance->mHotTypeData != NULL)
  21984. {
  21985. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  21986. {
  21987. BF_ASSERT(mCompiler->IsHotCompile());
  21988. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  21989. // may slot this override anyway (?)
  21990. int vTableStart = 0;
  21991. auto implBaseType = typeInstance->GetImplBaseType();
  21992. if (implBaseType != NULL)
  21993. vTableStart = implBaseType->mVirtualMethodTableSize;
  21994. StringT<512> mangledName;
  21995. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  21996. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  21997. {
  21998. // O(1) checking when virtual methods haven't changed
  21999. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  22000. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  22001. if (mangledName == entry.mFuncName)
  22002. {
  22003. virtualMethodMatchIdx = vTableStart + checkIdx;
  22004. break;
  22005. }
  22006. }
  22007. if (virtualMethodMatchIdx != -1)
  22008. {
  22009. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22010. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  22011. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  22012. }
  22013. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  22014. }
  22015. }
  22016. if (virtualMethodMatchIdx == -1)
  22017. {
  22018. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  22019. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  22020. typeInstance->mVirtualMethodTable.push_back(entry);
  22021. }
  22022. }
  22023. void BfModule::CompareDeclTypes(BfTypeInstance* typeInst, BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  22024. {
  22025. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  22026. {
  22027. // When we provide an extension override in the same project a root type override
  22028. isBetter = true;
  22029. isWorse = false;
  22030. }
  22031. else
  22032. {
  22033. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22034. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22035. }
  22036. if ((isBetter == isWorse) && (typeInst != NULL) && (newDeclType->IsExtension()) && (prevDeclType->IsExtension()))
  22037. {
  22038. if ((typeInst->mGenericTypeInfo != NULL) && (typeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL))
  22039. {
  22040. isBetter = false;
  22041. isWorse = false;
  22042. auto newConstraints = typeInst->GetGenericParamsVector(newDeclType);
  22043. auto prevConstraints = typeInst->GetGenericParamsVector(prevDeclType);
  22044. for (int genericIdx = 0; genericIdx < (int)newConstraints->size(); genericIdx++)
  22045. {
  22046. auto newConstraint = (*newConstraints)[genericIdx];
  22047. auto prevConstraint = (*prevConstraints)[genericIdx];
  22048. bool newIsSubset = AreConstraintsSubset(newConstraint, prevConstraint);
  22049. bool prevIsSubset = AreConstraintsSubset(prevConstraint, newConstraint);
  22050. if ((prevIsSubset) && (!newIsSubset))
  22051. isBetter = true;
  22052. if ((!prevIsSubset) && (newIsSubset))
  22053. isWorse = true;
  22054. }
  22055. }
  22056. }
  22057. }
  22058. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  22059. {
  22060. BP_ZONE("BfModule::SlotVirtualMethod");
  22061. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  22062. return false;
  22063. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  22064. {
  22065. if (!mCompiler->mOptions.mAllowHotSwapping)
  22066. return;
  22067. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  22068. return;
  22069. if (methodInstance->mHotMethod == NULL)
  22070. CheckHotMethod(methodInstance, "");
  22071. if (methodInstance->mHotMethod == NULL)
  22072. return;
  22073. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  22074. if (declMethodInstance->mHotMethod == NULL)
  22075. CheckHotMethod(declMethodInstance, "");
  22076. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  22077. virtualDecl->mRefCount++;
  22078. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  22079. };
  22080. auto typeInstance = mCurTypeInstance;
  22081. auto typeDef = typeInstance->mTypeDef;
  22082. auto methodDef = methodInstance->mMethodDef;
  22083. auto methodDeclaration = methodDef->GetMethodDeclaration();
  22084. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22085. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  22086. if (methodInstance->mIsInnerOverride)
  22087. return false;
  22088. BfAstNode* declaringNode = methodDeclaration;
  22089. if (propertyMethodDeclaration != NULL)
  22090. declaringNode = propertyMethodDeclaration->mNameNode;
  22091. BfMethodInstance* methodOverriden = NULL;
  22092. bool usedMethod = false;
  22093. BfTokenNode* virtualToken = NULL;
  22094. if (propertyDeclaration != NULL)
  22095. virtualToken = propertyDeclaration->mVirtualSpecifier;
  22096. else if (methodDeclaration != NULL)
  22097. virtualToken = methodDeclaration->mVirtualSpecifier;
  22098. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  22099. {
  22100. //Fail: Static members cannot be marked as override, virtual, or abstract
  22101. }
  22102. else if (methodDef->mIsVirtual)
  22103. {
  22104. if (IsHotCompile())
  22105. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  22106. BfTypeInstance* checkBase = typeInstance;
  22107. // If we are in an extension, look in ourselves first
  22108. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  22109. checkBase = checkBase->mBaseType;
  22110. if (typeInstance->IsValueType())
  22111. {
  22112. if (typeInstance->mBaseType == NULL)
  22113. return false; // It's actually ValueType
  22114. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  22115. if (!methodDef->mIsOverride)
  22116. {
  22117. Fail("Structs cannot have virtual methods", virtualToken, true);
  22118. return false;
  22119. }
  22120. checkBase = mContext->mBfObjectType;
  22121. if (checkBase->mVirtualMethodTableSize == 0)
  22122. PopulateType(checkBase, BfPopulateType_Full);
  22123. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  22124. return false; // System circular ref, don't do struct checking on those
  22125. }
  22126. int virtualMethodMatchIdx = -1;
  22127. bool hadHidingError = false;
  22128. BfMethodInstance* bestOverrideMethodInstance = NULL;
  22129. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  22130. int bestOverrideMethodIdx = -1;
  22131. int ambiguousOverrideMethodIdx = -1;
  22132. if (checkBase != NULL)
  22133. {
  22134. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22135. auto lookupType = checkBase;
  22136. while (lookupType != NULL)
  22137. {
  22138. lookupType->mTypeDef->PopulateMemberSets();
  22139. BfMethodDef* nextMethodDef = NULL;
  22140. BfMemberSetEntry* entry;
  22141. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  22142. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  22143. while (nextMethodDef != NULL)
  22144. {
  22145. auto checkMethodDef = nextMethodDef;
  22146. nextMethodDef = nextMethodDef->mNextWithSameName;
  22147. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  22148. continue;
  22149. BfMethodInstance* baseMethodInstance = NULL;
  22150. int checkMethodIdx = -1;
  22151. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  22152. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  22153. {
  22154. if (lookupType->IsUnspecializedTypeVariation())
  22155. {
  22156. if (!lookupMethodInstance->mMethodDef->mIsOverride)
  22157. {
  22158. baseMethodInstance = lookupMethodInstance;
  22159. checkMethodIdx = -2;
  22160. }
  22161. }
  22162. if (baseMethodInstance == NULL)
  22163. continue;
  22164. }
  22165. if (baseMethodInstance == NULL)
  22166. {
  22167. checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  22168. if (checkMethodIdx >= baseVirtualMethodTable.mSize)
  22169. {
  22170. Fail("SlotVirtualMethod out of bounds", checkMethodDef->GetRefNode());
  22171. continue;
  22172. }
  22173. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22174. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22175. {
  22176. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22177. continue;
  22178. }
  22179. baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22180. if (baseMethodInstance == NULL)
  22181. {
  22182. AssertErrorState();
  22183. continue;
  22184. }
  22185. }
  22186. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22187. {
  22188. if (methodDef->mIsOverride)
  22189. {
  22190. BfMethodInstance* checkMethodInstance;
  22191. if (checkMethodIdx == -2)
  22192. checkMethodInstance = baseMethodInstance;
  22193. else if (typeInstance->IsValueType())
  22194. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22195. else
  22196. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22197. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22198. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22199. continue;
  22200. if (bestOverrideMethodInstance != NULL)
  22201. {
  22202. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22203. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22204. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22205. if (isBetter == isWorse)
  22206. {
  22207. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22208. }
  22209. else
  22210. {
  22211. if (isWorse)
  22212. continue;
  22213. ambiguousOverrideMethodInstance = NULL;
  22214. }
  22215. }
  22216. bestOverrideMethodInstance = checkMethodInstance;
  22217. bestOverrideMethodIdx = checkMethodIdx;
  22218. }
  22219. else
  22220. {
  22221. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22222. {
  22223. if (!hadHidingError)
  22224. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22225. hadHidingError = true;
  22226. }
  22227. }
  22228. }
  22229. }
  22230. lookupType = lookupType->mBaseType;
  22231. }
  22232. }
  22233. //TODO:
  22234. if ((checkBase != NULL)
  22235. && (false)
  22236. )
  22237. {
  22238. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22239. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  22240. {
  22241. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22242. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22243. {
  22244. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22245. continue;
  22246. }
  22247. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22248. if (baseMethodInstance == NULL)
  22249. {
  22250. AssertErrorState();
  22251. continue;
  22252. }
  22253. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22254. {
  22255. if (methodDef->mIsOverride)
  22256. {
  22257. BfMethodInstance* checkMethodInstance;
  22258. if (typeInstance->IsValueType())
  22259. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22260. else
  22261. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22262. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22263. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22264. continue;
  22265. if (bestOverrideMethodInstance != NULL)
  22266. {
  22267. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22268. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22269. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22270. if (isBetter == isWorse)
  22271. {
  22272. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22273. }
  22274. else
  22275. {
  22276. if (isWorse)
  22277. continue;
  22278. ambiguousOverrideMethodInstance = NULL;
  22279. }
  22280. }
  22281. bestOverrideMethodInstance = checkMethodInstance;
  22282. bestOverrideMethodIdx = checkMethodIdx;
  22283. }
  22284. else
  22285. {
  22286. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22287. {
  22288. if (!hadHidingError)
  22289. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22290. hadHidingError = true;
  22291. }
  22292. }
  22293. }
  22294. }
  22295. }
  22296. if (bestOverrideMethodInstance != NULL)
  22297. {
  22298. if (ambiguousOverrideMethodInstance != NULL)
  22299. {
  22300. bool allow = false;
  22301. // 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.
  22302. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  22303. bool canSeeEachOther = false;
  22304. //
  22305. {
  22306. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  22307. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  22308. canSeeEachOther = true;
  22309. }
  22310. //
  22311. {
  22312. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  22313. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  22314. canSeeEachOther = true;
  22315. }
  22316. if (!canSeeEachOther)
  22317. {
  22318. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  22319. }
  22320. else
  22321. {
  22322. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  22323. if (error != NULL)
  22324. {
  22325. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  22326. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  22327. }
  22328. }
  22329. }
  22330. }
  22331. if (bestOverrideMethodIdx == -2)
  22332. {
  22333. // Comes from an unspecialized variation
  22334. virtualMethodMatchIdx = bestOverrideMethodIdx;
  22335. }
  22336. else if ((bestOverrideMethodInstance != NULL) && (bestOverrideMethodIdx != -1))
  22337. {
  22338. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22339. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  22340. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  22341. {
  22342. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  22343. {
  22344. BfTypeReference* returnTypeRef;
  22345. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22346. {
  22347. returnTypeRef = propertyDeclaration->mTypeRef;
  22348. Fail("Property differs from overridden property by type", returnTypeRef, true);
  22349. }
  22350. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22351. {
  22352. returnTypeRef = methodDeclaration->mReturnType;
  22353. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  22354. }
  22355. else
  22356. {
  22357. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  22358. }
  22359. return usedMethod;
  22360. }
  22361. }
  22362. if (methodDef->mIsOverride)
  22363. {
  22364. // We can have multiple matches when a virtual method is used to implement interface methods
  22365. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  22366. // vtable entries for this method signature
  22367. virtualMethodMatchIdx = bestOverrideMethodIdx;
  22368. if (!typeInstance->IsValueType())
  22369. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22370. if (typeInstance->IsValueType())
  22371. {
  22372. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22373. }
  22374. else
  22375. {
  22376. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22377. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  22378. BfMethodInstance* setMethodInstance = methodInstance;
  22379. bool doOverride = false;
  22380. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22381. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  22382. {
  22383. methodOverriden = overridenRef;
  22384. doOverride = true;
  22385. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  22386. {
  22387. bool isBetter = false;
  22388. bool isWorse = false;
  22389. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  22390. if (isBetter == isWorse)
  22391. {
  22392. // We have to resolve later per-project
  22393. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  22394. {
  22395. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22396. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  22397. }
  22398. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  22399. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  22400. doOverride = false;
  22401. }
  22402. else
  22403. {
  22404. if ((isBetter) && (ambiguityContext != NULL))
  22405. {
  22406. ambiguityContext->Remove(virtualMethodMatchIdx);
  22407. }
  22408. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  22409. {
  22410. if (preferRootDefinition)
  22411. {
  22412. // Leave the master GCMarkMember
  22413. isBetter = false;
  22414. isWorse = true;
  22415. }
  22416. }
  22417. doOverride = isBetter;
  22418. }
  22419. }
  22420. }
  22421. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  22422. {
  22423. methodOverriden = overridenRef;
  22424. doOverride = true;
  22425. }
  22426. if (doOverride)
  22427. {
  22428. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22429. _AddVirtualDecl(declMethodInstance);
  22430. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22431. auto& implMethodRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22432. if ((!mCompiler->mIsResolveOnly) && (implMethodRef.mMethodNum >= 0) &&
  22433. (implMethodRef.mTypeInstance == typeInstance) && (methodInstance->GetOwner() == typeInstance))
  22434. {
  22435. auto prevImplMethodInstance = (BfMethodInstance*)implMethodRef;
  22436. if (prevImplMethodInstance->mMethodDef->mDeclaringType->mProject != methodInstance->mMethodDef->mDeclaringType->mProject)
  22437. {
  22438. // We may need to have to previous method reified when we must re-slot in another project during vdata creation
  22439. BfReifyMethodDependency dep;
  22440. dep.mDepMethod = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22441. dep.mMethodIdx = implMethodRef.mMethodNum;
  22442. typeInstance->mReifyMethodDependencies.Add(dep);
  22443. }
  22444. if (!methodInstance->mMangleWithIdx)
  22445. {
  22446. // Keep mangled names from conflicting
  22447. methodInstance->mMangleWithIdx = true;
  22448. if ((methodInstance->mIRFunction) && (methodInstance->mDeclModule->mIsModuleMutable))
  22449. {
  22450. StringT<4096> mangledName;
  22451. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  22452. methodInstance->mDeclModule->mBfIRBuilder->SetFunctionName(methodInstance->mIRFunction, mangledName);
  22453. }
  22454. }
  22455. }
  22456. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  22457. }
  22458. }
  22459. if (methodOverriden != NULL)
  22460. {
  22461. CheckOverridenMethod(methodInstance, methodOverriden);
  22462. }
  22463. }
  22464. }
  22465. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  22466. {
  22467. if (methodDef->mIsOverride)
  22468. {
  22469. BfTokenNode* overrideToken = NULL;
  22470. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  22471. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  22472. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22473. overrideToken = methodDeclaration->mVirtualSpecifier;
  22474. if (overrideToken != NULL)
  22475. {
  22476. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  22477. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  22478. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  22479. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  22480. else
  22481. Fail("No suitable method found to override", overrideToken, true);
  22482. }
  22483. return usedMethod;
  22484. }
  22485. UniqueSlotVirtualMethod(methodInstance);
  22486. }
  22487. else
  22488. usedMethod = true;
  22489. if (typeInstance->IsValueType())
  22490. return usedMethod;
  22491. }
  22492. bool foundInterface = false;
  22493. bool hadAnyMatch = false;
  22494. // See if this method matches interfaces
  22495. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  22496. {
  22497. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  22498. if (ifaceInst->IsIncomplete())
  22499. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  22500. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  22501. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  22502. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  22503. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  22504. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  22505. continue;
  22506. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  22507. continue;
  22508. bool hadMatch = false;
  22509. BfMethodInstance* hadNameMatch = NULL;
  22510. BfType* expectedReturnType = NULL;
  22511. bool showedError = false;
  22512. // We go through our VTable looking for NULL entries within the interface sections
  22513. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  22514. // because a normal method declared in this type could have matched earlier
  22515. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  22516. ifaceInst->mTypeDef->PopulateMemberSets();
  22517. BfMethodDef* checkMethodDef = NULL;
  22518. BfMemberSetEntry* entry;
  22519. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  22520. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  22521. while (checkMethodDef != NULL)
  22522. {
  22523. int iMethodIdx = checkMethodDef->mIdx;
  22524. int iTableIdx = iMethodIdx + startIdx;
  22525. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  22526. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  22527. bool storeIFaceMethod = false;
  22528. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  22529. {
  22530. checkMethodDef = checkMethodDef->mNextWithSameName;
  22531. continue;
  22532. }
  22533. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  22534. auto iMethodInst = iMethodGroup.mDefault;
  22535. if (iMethodInst == NULL)
  22536. {
  22537. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  22538. AssertErrorState();
  22539. checkMethodDef = checkMethodDef->mNextWithSameName;
  22540. continue;
  22541. }
  22542. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  22543. hadNameMatch = iMethodInst;
  22544. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  22545. if ((!doesMethodSignatureMatch) && (interfaceMethodEntry->mMethodRef.IsNull()))
  22546. {
  22547. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  22548. }
  22549. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  22550. {
  22551. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  22552. {
  22553. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  22554. {
  22555. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  22556. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  22557. if (error != NULL)
  22558. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  22559. showedError = true;
  22560. }
  22561. }
  22562. }
  22563. if (doesMethodSignatureMatch)
  22564. {
  22565. usedMethod = true;
  22566. hadMatch = true;
  22567. hadAnyMatch = true;
  22568. storeIFaceMethod = true;
  22569. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  22570. {
  22571. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  22572. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance) && (!mIsComptimeModule))
  22573. {
  22574. // When autocompletion regenerates a single method body but not the whole type then
  22575. // we will see ourselves in the vtable already
  22576. return usedMethod;
  22577. }
  22578. bool isBetter = false;
  22579. bool isWorse = false;
  22580. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  22581. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  22582. if (isBetter == isWorse)
  22583. {
  22584. isBetter = methodInstance->mReturnType == iMethodInst->mReturnType;
  22585. isWorse = prevMethod->mReturnType == iMethodInst->mReturnType;
  22586. }
  22587. if (isBetter == isWorse)
  22588. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  22589. if (isBetter == isWorse)
  22590. {
  22591. if (ambiguityContext != NULL)
  22592. {
  22593. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  22594. }
  22595. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  22596. storeIFaceMethod = true;
  22597. }
  22598. else
  22599. {
  22600. if ((isBetter) && (ambiguityContext != NULL))
  22601. ambiguityContext->Remove(~iTableIdx);
  22602. storeIFaceMethod = isBetter;
  22603. }
  22604. }
  22605. }
  22606. if (storeIFaceMethod)
  22607. {
  22608. if (methodInstance->GetNumGenericParams() != 0)
  22609. _AddVirtualDecl(iMethodInst);
  22610. *iMethodPtr = methodInstance;
  22611. }
  22612. checkMethodDef = checkMethodDef->mNextWithSameName;
  22613. }
  22614. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  22615. {
  22616. if (expectedReturnType != NULL)
  22617. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  22618. else if (hadNameMatch != NULL)
  22619. {
  22620. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  22621. if (error != NULL)
  22622. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  22623. }
  22624. else
  22625. {
  22626. auto propertyDecl = methodDef->GetPropertyDeclaration();
  22627. if (propertyDecl != NULL)
  22628. {
  22629. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  22630. String name;
  22631. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  22632. name = "this[]";
  22633. else if (propertyDecl->mNameNode != NULL)
  22634. propertyDecl->mNameNode->ToString(name);
  22635. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  22636. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  22637. }
  22638. else
  22639. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  22640. }
  22641. }
  22642. }
  22643. // Any overriden virtual methods that were used in interfaces also need to be replaced
  22644. if (methodOverriden != NULL)
  22645. {
  22646. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  22647. {
  22648. if (methodEntry.mMethodRef == methodOverriden)
  22649. methodEntry.mMethodRef = methodInstance;
  22650. }
  22651. }
  22652. return usedMethod;
  22653. }
  22654. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  22655. {
  22656. auto methodDef = methodInstance->mMethodDef;
  22657. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  22658. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  22659. {
  22660. const char* protectionNames[] = { "disabled", "hidden", "private", "internal", "protected", "protected internal", "public" };
  22661. BF_STATIC_ASSERT(BF_ARRAY_COUNT(protectionNames) == BfProtection_COUNT);
  22662. BfAstNode* protectionRefNode = NULL;
  22663. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  22664. {
  22665. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  22666. if (protectionRefNode == NULL)
  22667. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  22668. if (protectionRefNode == NULL)
  22669. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  22670. }
  22671. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22672. {
  22673. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  22674. if (protectionRefNode == NULL)
  22675. protectionRefNode = methodDeclaration->mNameNode;
  22676. }
  22677. if (protectionRefNode != NULL)
  22678. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  22679. }
  22680. }
  22681. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  22682. {
  22683. auto typeInstance = mCurTypeInstance;
  22684. auto methodDef = methodInstance->mMethodDef;
  22685. if (methodDef->mMethodType == BfMethodType_Ctor)
  22686. return true;
  22687. bool foundOverride = false;
  22688. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  22689. {
  22690. auto methodDeclaration = methodDef->GetMethodDeclaration();
  22691. BfAstNode* refNode = NULL;
  22692. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22693. refNode = propertyDeclaration->mProtectionSpecifier;
  22694. else if (methodDeclaration != NULL)
  22695. refNode = methodDeclaration->mProtectionSpecifier;
  22696. Fail("Private interface methods must provide a body", refNode);
  22697. }
  22698. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  22699. {
  22700. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  22701. }
  22702. BfAstNode* declaringNode = methodDef->GetRefNode();
  22703. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  22704. {
  22705. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  22706. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  22707. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  22708. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  22709. continue;
  22710. ifaceInst->mTypeDef->PopulateMemberSets();
  22711. BfMethodDef* nextMethod = NULL;
  22712. BfMemberSetEntry* entry = NULL;
  22713. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22714. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22715. while (nextMethod != NULL)
  22716. {
  22717. auto checkMethod = nextMethod;
  22718. nextMethod = nextMethod->mNextWithSameName;
  22719. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22720. if (ifaceMethod == NULL)
  22721. continue;
  22722. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22723. {
  22724. if (methodDef->mIsOverride)
  22725. {
  22726. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  22727. {
  22728. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  22729. if (error != NULL)
  22730. {
  22731. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  22732. }
  22733. }
  22734. foundOverride = true;
  22735. }
  22736. else if (!methodDef->mIsNew)
  22737. {
  22738. 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);
  22739. if (error != NULL)
  22740. {
  22741. mCompiler->mPassInstance->MoreInfo("See inherited method", ifaceMethod->mMethodDef->GetRefNode());
  22742. }
  22743. }
  22744. }
  22745. }
  22746. }
  22747. if ((methodDef->mIsOverride) && (!foundOverride))
  22748. {
  22749. // This allows us to declare a method in the base definition or in an extension and then provide
  22750. // an implementation in a more-specific extension
  22751. typeInstance->mTypeDef->PopulateMemberSets();
  22752. BfMethodDef* nextMethod = NULL;
  22753. BfMemberSetEntry* entry = NULL;
  22754. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22755. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22756. while (nextMethod != NULL)
  22757. {
  22758. auto checkMethod = nextMethod;
  22759. nextMethod = nextMethod->mNextWithSameName;
  22760. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22761. if (ifaceMethod == NULL)
  22762. continue;
  22763. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  22764. continue;
  22765. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22766. {
  22767. foundOverride = true;
  22768. }
  22769. }
  22770. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  22771. // {
  22772. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  22773. // if (ifaceMethod == NULL)
  22774. // continue;
  22775. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  22776. // continue;
  22777. //
  22778. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22779. // {
  22780. // foundOverride = true;
  22781. // }
  22782. // }
  22783. }
  22784. if (methodDef->mIsOverride)
  22785. {
  22786. if (!foundOverride)
  22787. {
  22788. BfTokenNode* overrideToken = NULL;
  22789. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22790. overrideToken = propertyDeclaration->mVirtualSpecifier;
  22791. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22792. overrideToken = methodDeclaration->mVirtualSpecifier;
  22793. if (overrideToken != NULL)
  22794. {
  22795. Fail("No suitable method found to override", overrideToken, true);
  22796. }
  22797. else
  22798. {
  22799. // Possible cause - DTOR with params
  22800. AssertErrorState();
  22801. }
  22802. }
  22803. return true;
  22804. }
  22805. // Generic methods can't be called virtually
  22806. if (methodInstance->GetNumGenericParams() != 0)
  22807. return true;
  22808. // Only public methods can be called virtually
  22809. if (methodDef->mProtection != BfProtection_Public)
  22810. return true;
  22811. UniqueSlotVirtualMethod(methodInstance);
  22812. return true;
  22813. }
  22814. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  22815. {
  22816. if (methodInstance->mMethodInfoEx == NULL)
  22817. return;
  22818. int wantMinDepth = -1;
  22819. if (mCurTypeInstance != NULL)
  22820. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  22821. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  22822. {
  22823. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  22824. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  22825. wantMinDepth = wantTypeMinDepth;
  22826. }
  22827. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  22828. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  22829. }
  22830. void BfModule::DbgFinish()
  22831. {
  22832. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  22833. return;
  22834. if (mAwaitingInitFinish)
  22835. FinishInit();
  22836. if (mHasForceLinkMarker)
  22837. return;
  22838. String markerName;
  22839. BfIRValue linkMarker;
  22840. if (mBfIRBuilder->DbgHasInfo())
  22841. {
  22842. bool needForceLinking = false;
  22843. if (WantsDebugHelpers())
  22844. {
  22845. for (auto& ownedType : mOwnedTypeInstances)
  22846. {
  22847. bool hasConfirmedReference = false;
  22848. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  22849. {
  22850. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  22851. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  22852. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)) &&
  22853. (methodInstGroup.mHasEmittedReference))
  22854. {
  22855. hasConfirmedReference = true;
  22856. }
  22857. }
  22858. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  22859. needForceLinking = true;
  22860. }
  22861. }
  22862. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  22863. {
  22864. BfMethodState methodState;
  22865. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  22866. methodState.mTempKind = BfMethodState::TempKind_Static;
  22867. mHasForceLinkMarker = true;
  22868. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  22869. SizedArray<BfIRType, 0> paramTypes;
  22870. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  22871. String linkName = "FORCELINKMOD_" + mModuleName;
  22872. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  22873. mBfIRBuilder->SetActiveFunction(func);
  22874. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  22875. mBfIRBuilder->SetInsertPoint(entryBlock);
  22876. auto firstType = mOwnedTypeInstances[0];
  22877. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  22878. SizedArray<BfIRMDNode, 1> diParamTypes;
  22879. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  22880. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  22881. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  22882. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  22883. methodState.mCurScope->mDIScope = diScope;
  22884. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  22885. SizedArray<BfIRValue, 8> args;
  22886. BfExprEvaluator exprEvaluator(this);
  22887. for (auto& ownedType : mOwnedTypeInstances)
  22888. {
  22889. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  22890. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  22891. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  22892. }
  22893. mBfIRBuilder->CreateRetVoid();
  22894. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  22895. }
  22896. }
  22897. }
  22898. bool BfModule::Finish()
  22899. {
  22900. BP_ZONE("BfModule::Finish");
  22901. BfLogSysM("BfModule finish: %p\n", this);
  22902. if (mHadBuildError)
  22903. {
  22904. // Don't AssertErrorState here, this current pass may not have failed but
  22905. // the module was still queued in mFinishedModuleWorkList
  22906. ClearModule();
  22907. return true;
  22908. }
  22909. if (mUsedSlotCount != -1)
  22910. {
  22911. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  22912. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  22913. }
  22914. if ((!mGeneratesCode) && (!mAddedToCount))
  22915. return true;
  22916. BF_ASSERT(mAddedToCount);
  22917. mAddedToCount = false;
  22918. mAwaitingFinish = false;
  22919. mCompiler->mStats.mModulesFinished++;
  22920. if (HasCompiledOutput())
  22921. {
  22922. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  22923. DbgFinish();
  22924. if (mAwaitingInitFinish)
  22925. FinishInit();
  22926. for (auto ownedTypeInst : mOwnedTypeInstances)
  22927. {
  22928. // Generate dbg info and add global variables if we haven't already
  22929. mBfIRBuilder->PopulateType(ownedTypeInst);
  22930. }
  22931. if (mBfIRBuilder->DbgHasInfo())
  22932. {
  22933. mBfIRBuilder->DbgFinalize();
  22934. }
  22935. String objOutputPath;
  22936. String irOutputPath;
  22937. mIsModuleMutable = false;
  22938. //mOutFileNames.Clear();
  22939. BF_ASSERT(((int)mOutFileNames.size() >= mExtensionCount) || (mParentModule != NULL));
  22940. bool writeModule = mBfIRBuilder->HasExports();
  22941. String outputPath;
  22942. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  22943. auto& compilerOpts = mCompiler->mOptions;
  22944. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  22945. auto moduleOptions = GetModuleOptions();
  22946. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  22947. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  22948. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  22949. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  22950. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  22951. codeGenOptions.mVirtualMethodOfs = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  22952. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  22953. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  22954. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  22955. bool allowWriteToLib = true;
  22956. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  22957. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  22958. {
  22959. codeGenOptions.mWriteToLib = true;
  22960. mWroteToLib = true;
  22961. }
  22962. else
  22963. {
  22964. mWroteToLib = false;
  22965. }
  22966. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  22967. {
  22968. outputPath = mModuleName;
  22969. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  22970. BfModuleFileName moduleFileName;
  22971. if (mParentModule != NULL)
  22972. {
  22973. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  22974. {
  22975. if (checkPair.mValue == this)
  22976. moduleFileName.mProjects = checkPair.mKey;
  22977. }
  22978. }
  22979. moduleFileName.mProjects.Add(mProject);
  22980. if (fileIdx > 0)
  22981. outputPath += StrFormat("@%d", fileIdx + 1);
  22982. if (mCompiler->mOptions.mWriteIR)
  22983. irOutputPath = outputPath + ".ll";
  22984. if (mCompiler->mOptions.mGenerateObj)
  22985. {
  22986. objOutputPath = outputPath + BF_OBJ_EXT;
  22987. moduleFileName.mFileName = objOutputPath;
  22988. }
  22989. else if (mCompiler->mOptions.mWriteIR)
  22990. {
  22991. moduleFileName.mFileName = irOutputPath;
  22992. }
  22993. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  22994. {
  22995. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  22996. }
  22997. moduleFileName.mModuleWritten = writeModule;
  22998. moduleFileName.mWroteToLib = mWroteToLib;
  22999. if (!mOutFileNames.Contains(moduleFileName))
  23000. mOutFileNames.Add(moduleFileName);
  23001. }
  23002. if (mCompiler->IsHotCompile())
  23003. {
  23004. codeGenOptions.mIsHotCompile = true;
  23005. if (mParentModule != NULL)
  23006. mParentModule->mHadHotObjectWrites = true;
  23007. mHadHotObjectWrites = true;
  23008. }
  23009. //TODO: Testing VDATA
  23010. /*if (mModuleName == "vdata")
  23011. {
  23012. codeGenOptions.mOptLevel = 4;
  23013. }*/
  23014. codeGenOptions.GenerateHash();
  23015. BP_ZONE("BfModule::Finish.WriteObjectFile");
  23016. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  23017. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  23018. mLastModuleWrittenRevision = mCompiler->mRevision;
  23019. }
  23020. else
  23021. {
  23022. for (auto type : mOwnedTypeInstances)
  23023. {
  23024. BF_ASSERT((!type->IsIncomplete()) || (type->IsSpecializedByAutoCompleteMethod()));
  23025. }
  23026. }
  23027. for (auto& specModulePair : mSpecializedMethodModules)
  23028. {
  23029. auto specModule = specModulePair.mValue;
  23030. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  23031. {
  23032. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  23033. }
  23034. }
  23035. CleanupFileInstances();
  23036. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  23037. return true;
  23038. }
  23039. void BfModule::ReportMemory(MemReporter* memReporter)
  23040. {
  23041. memReporter->Add(sizeof(BfModule));
  23042. if (mBfIRBuilder != NULL)
  23043. {
  23044. memReporter->BeginSection("IRBuilder_ConstData");
  23045. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  23046. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  23047. memReporter->EndSection();
  23048. memReporter->BeginSection("IRBuilder_BFIR");
  23049. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  23050. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  23051. memReporter->EndSection();
  23052. memReporter->Add(sizeof(BfIRBuilder));
  23053. }
  23054. memReporter->BeginSection("FileInstanceMap");
  23055. memReporter->AddMap(mFileInstanceMap);
  23056. memReporter->AddMap(mNamedFileInstanceMap);
  23057. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  23058. memReporter->EndSection();
  23059. memReporter->AddVec(mOwnedTypeInstances, false);
  23060. memReporter->AddVec(mSpecializedMethodModules, false);
  23061. memReporter->AddVec(mOutFileNames, false);
  23062. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  23063. memReporter->AddMap(mInterfaceSlotRefs, false);
  23064. memReporter->AddMap(mStaticFieldRefs, false);
  23065. memReporter->AddMap(mClassVDataRefs, false);
  23066. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  23067. memReporter->AddMap(mTypeDataRefs, false);
  23068. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  23069. memReporter->AddMap(mDeferredMethodCallData, false);
  23070. memReporter->AddHashSet(mDeferredMethodIds, false);
  23071. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  23072. }
  23073. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  23074. // be transient through the next compile
  23075. void BfModule::ClearModuleData(bool clearTransientData)
  23076. {
  23077. BfLogSysM("ClearModuleData %p\n", this);
  23078. if (mAddedToCount)
  23079. {
  23080. mCompiler->mStats.mModulesFinished++;
  23081. mAddedToCount = false;
  23082. }
  23083. mDICompileUnit = BfIRMDNode();
  23084. if (clearTransientData)
  23085. mIncompleteMethodCount = 0;
  23086. mHasGenericMethods = false;
  23087. // We don't want to clear these because we want it to persist through module extensions-
  23088. // otherwise we may think an extension succeeds even though the base module failed
  23089. //mHadBuildError = false;
  23090. //mHadBuildWarning = false;
  23091. mClassVDataRefs.Clear();
  23092. mClassVDataExtRefs.Clear();
  23093. for (auto& kv : mTypeDataRefs)
  23094. kv.mValue = BfIRValue();
  23095. mStringCharPtrPool.Clear();
  23096. mStringObjectPool.Clear();
  23097. mStaticFieldRefs.Clear();
  23098. BF_ASSERT(!mIgnoreErrors);
  23099. for (auto prevIRBuilder : mPrevIRBuilders)
  23100. delete prevIRBuilder;
  23101. mPrevIRBuilders.Clear();
  23102. for (auto& specPair : mSpecializedMethodModules)
  23103. {
  23104. auto specModule = specPair.mValue;
  23105. specModule->ClearModuleData();
  23106. }
  23107. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  23108. mBuiltInFuncs[i] = BfIRFunction();
  23109. if (mNextAltModule != NULL)
  23110. mNextAltModule->ClearModuleData();
  23111. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  23112. mIsModuleMutable = false;
  23113. delete mBfIRBuilder;
  23114. mBfIRBuilder = NULL;
  23115. mWantsIRIgnoreWrites = false;
  23116. }
  23117. void BfModule::DisownMethods()
  23118. {
  23119. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  23120. mBuiltInFuncs[i] = BfIRFunction();
  23121. BfModule* methodModule = this;
  23122. if (mParentModule != NULL)
  23123. methodModule = mParentModule;
  23124. for (auto typeInst : methodModule->mOwnedTypeInstances)
  23125. {
  23126. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  23127. {
  23128. if (methodGroup.mDefault != NULL)
  23129. {
  23130. if (methodGroup.mDefault->mIRFunction)
  23131. {
  23132. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  23133. if (methodGroup.mDefault->mDeclModule == this)
  23134. {
  23135. methodGroup.mDefault->mIRFunction = BfIRFunction();
  23136. }
  23137. }
  23138. }
  23139. if (methodGroup.mMethodSpecializationMap != NULL)
  23140. {
  23141. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  23142. {
  23143. auto methodInstance = mapPair.mValue;
  23144. if (methodInstance->mDeclModule == this)
  23145. {
  23146. methodInstance->mIRFunction = BfIRFunction();
  23147. }
  23148. }
  23149. }
  23150. }
  23151. }
  23152. }
  23153. void BfModule::ClearModule()
  23154. {
  23155. ClearModuleData();
  23156. DisownMethods();
  23157. for (auto& specPair : mSpecializedMethodModules)
  23158. {
  23159. auto specModule = specPair.mValue;
  23160. specModule->ClearModule();
  23161. }
  23162. if (mNextAltModule != NULL)
  23163. mNextAltModule->ClearModule();
  23164. }